Click here to Skip to main content
14,364,354 members
Rate this:
Please Sign up or sign in to vote.
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 6:07am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

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?
   
Comments
Member 13908127 6-Nov-19 1:38am
   
The 'data' return exception message "Authentication failed",and 'data.d' return 'undefined'
Rate this:
Please Sign up or sign in to vote.

Solution 1

data: JSON.stringify({"name" : uname}),
   
Comments
Member 13908127 6-Nov-19 1:57am
   
Thanks,not working
Rate this:
Please Sign up or sign in to vote.

Solution 3

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.
	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
	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?
   
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100