Learn12 Learn12 - 6 months ago 8
Ajax Question

JQuery AJAX request not working.

I am using AJAX for the first time and I am not sure if I have the correct syntax down. Basically I have a method in the behind code that takes in 2 string parameters and executes an updates the users password. But it keeps coming back as failed.

Here is my current asp button:

<td><asp:Button ID="Button1" runat="server" Text="Add Password" alt="Add Password" /></td>


This is the code that executes once the user hits the Add Password button on the form:

$("#edit_password_form").submit(function (e) {
e.preventDefault();

var finalValue = value2.value;

<%string inputCust = Session[SessionKey.CUSTOMER_ID].ToString();%>
var custNoString = <%=inputCust%>

$.ajax({
url: 'reciept.aspx/Button1_Click',
method: 'post',
contentType: 'application/json',
data: '{custID:' + custNoString + 'tempPass2:' + finalValue + '}',
success: function(){

alert("The function worked correctly");

},
error:function(){ alert("the function did not succeed");}
});
});;


Any ideas on why it could be failing? Mayb I am missing an ajax key or my syntax could be off.

Let me know! Thanks.

Answer

Data parameters need properly created JSON. You are missing out on some single quotes here and there.

Instead of manually creating the JSON string, try creating an object first, then stringify it for data. Refer to the code below:

 $("#edit_password_form").submit(function (e) {
                         e.preventDefault();

                         var finalValue = value2.value;

                         <%string inputCust = Session[SessionKey.CUSTOMER_ID].ToString();%>
                         var custNoString = <%=inputCust%>

                         var dataObj = {};
                         dataObj.custID = custNoString;
                         dataObj.tempPass2 = finalValue;

                         $.ajax({
                             url: 'reciept.aspx/Button1_Click',
                             method: 'post',
                             contentType: 'application/json',
                             data: JSON.stringify(dataObj),
                             success: function(){

                                 alert("The function worked correctly");

                             },
                             error:function(){ alert("the function did not succeed");}
                         });
                     });;