how do i define the success and failure function of an ajax $.post?
You can check when exactly it returns "success" : // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { ... // If not modified if ( status === 304 ) { statusText = "notmodified"; ... // If we have data } else { try { ...
Note that in your success event, the data parameter usually represents elements within the response of your request, in the format of JSON. So, within the response, set a JSON object with a parameter called returnValue with either true or false value. Then, you could access this value via data. returnValue .
jQuery ajaxStop() Method The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.
//your jquery code will be like this: $. ajax({ type: 'POST', url: $url, data: new FormData(this), dataType: 'json', contentType: false, processData:false,//this is a must success: function(response){ $('your_selector'). html(response); } }); //php code will be like this echo '<div>some html code</div>'; die();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With