Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I use ajax call codebehind method not working.I am a beginner,someone can help?

AjaxTest.aspx code:



function ShowCurrentTime() {
var uname = document.getElementById("txtUserName").value;
$.ajax({
type: "POST",
url: "AjaxTest.aspx/GetCurrentTime",
data: "{'name':'" + uname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response);
}
});
}
function OnSuccess(data) {
if (data.d != null) {
alert(data.d);
}
else {
alert("Null object!");
}
}

AjaxTest.aspx.cs code:

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}

result:
return 'Null object!'

What I have tried:

I download different jquery.js,but no use.
Posted
Updated 6-Nov-19 5:07am
v2

Change it to:
if (data != null) {
alert(data);
console.log(data); // to check what value is returned. or error code. //
}

I would suggest to see what comes in data. What is data.d?
 
Share this answer
 
Comments
Member 13908127 6-Nov-19 1:38am    
The 'data' return exception message "Authentication failed",and 'data.d' return 'undefined'
data: JSON.stringify({"name" : uname}),
 
Share this answer
 
Comments
Member 13908127 6-Nov-19 1:57am    
Thanks,not working
Answer #1 from this SO post shows a few differences
https://stackoverflow.com/questions/10127937/calling-a-pages-webmethod-from-javascript-on-a-different-page


Your problem most likely lies with the success portion of your method; you are calling a separate function and not giving it any data to work with.
JavaScript
	success: OnSuccess,
	failure: function (response) { alert(response); }
-- skip down --
function OnSuccess(data) {
	if (data.d != null) { alert(data.d); }
	else { alert("Null object!"); }
}
And the first thing I would try is passing that data explicitly to your OnSuccess function
JavaScript
	success: OnSuccess(response),
-- OR --
	success: function(response) { OnSuccess(response); },


From reading the other answers and comments; it is looking like you are having an issue with Authentication. Is there a log-in requirement that needs to be met?
 
Share this answer
 
Comments
Member 13908127 7-Nov-19 21:36pm    
Thank you every much!
After modifying redirectmode to off in RouteConfig.cs,it work normally.

//settings.AutoRedirectMode = RedirectMode.Permanent;
settings.AutoRedirectMode = RedirectMode.Off;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900