Reputation: 216
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.
Upvotes: 1
Views: 207
Reputation: 20467
(Posted as answer on behalf of the OP).
This is what ended up working for me:
// Create the data object for the 2 parameters for the c# Method
var dataObj = { custID1: custNoString, tempPass2: finalValue };
// AJAX request for run the function
$.ajax({
type: 'post',
url: 'reciept.aspx/Button1_Click',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dataObj),
success: function(){
alert("The function worked correctly");
},
error:function(){ alert("the function did not succeed");}
});
Creating the data object first was the key. Thank you for all your help and suggestions!
Upvotes: 0
Reputation: 1715
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");}
});
});;
Upvotes: 1
Reputation: 10600
it is not correct syntax to post data: data: '{custID:' + custNoString + 'tempPass2:' + finalValue + '}'
try to pass your data by json format this way data: { custID: custNoString, tempPass2: finalValue }
otherwise it should not work .
more check this link http://www.json.org/JSONRequest.html
Upvotes: 1