Success callback not working properly for $.ajax
I have a problem which is similar to this stackoverflow
I am sending a list of selected objects to an "Update" method. That works fine, the problem is on the success callback. It does not happen for some reason. The page jus开发者_运维技巧t sort of blinks once. In firebug's net tab I can see call to the url. The controller returns bool so in the Response I just have true
. But obviously what I want to do is update the page based on that bool. This is MVC2 project-not sure if this has to do with it.
$.ajax({
url: "/Update/UpdateAll",
dataType: 'json',
type: "POST",
data: { selected: selected, statusID: statusID },
success: function (result) {
if (result) {
alert('all successful');
$('#resultsFromUpdate').html("Success");
}
else {
alert('no deal');
$('#resultsFromUpdate').html("Fail");
}
}
});
and UpdateAll
controller method:
public bool UpdateAll(string selected, string statusID)
{
...
> update some things
> return true if fine
> return fasle if not
...
}
This is exactly the point of using AJAX, not requiring a page post...So what am I doing wrong ?
Should really have a JsonResult as your return type, as you specified "json" as what the $.ajax method should expect. Also, the $.post method is usually easier to use.
This is a good place to delve into the arsenal of free debugging tools web developers have.
Note that Chrome, Firefox and IE9 all provide developer tools (just press F12 for IE9). These allow you to step through the code and observe the variables that returned.
You can also use fiddler to examine the content passed between the browser and visual studio.
Note that JSON-enabled WCF services written in ASP.NET 3.5 return an object where the return value is a data member d
.
You can try this:
$.ajax({
url: "/Update/UpdateAll",
dataType: 'json',
type: "POST",
data: { selected: selected, statusID: statusID },
success: function (result) {
/* NOTE: Not checking result, but result.d */
if (result.d) {
alert('all successful');
$('#resultsFromUpdate').html("Success");
}
else {
alert('no deal');
$('#resultsFromUpdate').html("Fail");
}
}
});
If I guessed it right I'm buying a lottery ticket :-)
My advice is to use Firebug or other Javascript debugging tool and/or specify 'error' callback at least with an 'alert' in it besides 'success'. Maybe MIME type sent by the server is not matched, or there can be some other reason.
精彩评论