First off, I know there are so many questions that are similar to this, but none of them have helped in my particular case (it's likely that I just need clarification, and I don't want to open an old thread).
I am creating an application and I need to call a C# method within a jQuery function. The reason I need to do this, is because I need to perform a query to a database using two specific parameters.
Javascript:
$(".button").click(function(){
var dataId = $(this).attr("data-Id");
var s = PageMethods.returnStr(dataId, onSuccess, onError);
function onSuccess(result){
alert(s);
}
function onError(result){
alert("error");
}
});
C#:
[WebMethod]
public static string returnStr(string Id)
{
// ... blah blah make query, return string s
return s;
}
The returned string is undefined. If I use alert(result), I just get the syntax of the page.
I've also tried to reference a c# variable using:
C#
public static string s;
JavaScript:
alert('<%=s%>');
and this works, but then when I call the WebMethod, I cannot modify s.
One last thing I've tried is ajax, but even if I model it off of answers found on SO, I cannot get it to work as I'd like it to - it returns "[object Object]":
AJAX:
$.ajax({
type: "POST",
url: "default.aspx/returnStr",
dataType: "json",
contentType: 'application/json; charset=utf-8',
error: function(result){
alert("request failed" + result)
},
success: function(result){
alert(result);
}
});
Any advice at all is greatly appreciated!!
PageMethods.alert()to debug. Useconsole.log(result)instead