When executing an ajax request using jQuery I am not sure how to add a variable to the data that is being sent to the server. Sending a request with a static string works fine:
$("#btnSubmit").click(function () {
var inputtext = $("#txtInput").val();
$.ajax({
type: "POST",
url: "Webform1.aspx/Function",
data: "{'ans':'hello'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
The above calls the .net function and then produces a msgbox with the response string.
How can I replace the hard coded string 'hello' with a variable such as the inputtext variable above.
The following does not work and results in 500 errors that relate to json parsing:
{'ans':inputtext}
{ans:inputtext}
{"ans":inputtext}
(ans is the name of the function parameter)
Edit:
To process the request server side I just use the .net WebMethod attribute for the function, which works with the hard-coded string request in the above example but simply returns the entire html page when passed a variable using data: {ans:inputtext}:
[System.Web.Services.WebMethod]
public static string Function(string ans)
{
return ans;
}