Jquery checking success of ajax post
The documentation is here: http://docs.jquery.com/Ajax/jQuery.ajax
But, to summarize, the ajax call takes a bunch of options. the ones you are looking for are error and success.
You would call it like this:
$.ajax({
url: 'mypage.html',
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
I have shown the success and error function taking no arguments, but they can receive arguments.
The error function can take three arguments: XMLHttpRequest, textStatus, and errorThrown.
The success function can take two arguments: data and textStatus. The page you requested will be in the data argument.
If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.
Instead of this:
$.post("/post/url.php", parameters, successFunction);
you would use this:
$.ajax({
url: "/post/url.php",
type: "POST",
data: parameters,
success: successFunction,
error: errorFunction
});
There are lots of other options available too. The documentation lists all the options available.
using jQuery 1.8 and above, should use the following:
var request = $.ajax({
type: 'POST',
url: 'mmm.php',
data: { abc: "abcdefghijklmnopqrstuvwxyz" } })
.done(function(data) { alert("success"+data.slice(0, 100)); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
check out the docs as @hitautodestruct stated.
I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:
original Code block:
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
Changed Code block:
post: function (url, data, callback, failcallback, type) {
if (type === undefined || type === null) {
if (!jQuery.isFunction(failcallback)) {
type=failcallback
}
else if (!jQuery.isFunction(callback)) {
type = callback
}
}
if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
failcallback = callback;
}
// shift arguments if data argument was omited
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
error:failcallback,
dataType: type
});
},
This should help the one trying to catch error on $.Post in jquery.
Updated: Or there is another way to do this is :
$.post(url,{},function(res){
//To do write if call is successful
}).error(function(p1,p2,p3){
//To do Write if call is failed
});