Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery checking success of ajax post

Tags:

jquery

how do i define the success and failure function of an ajax $.post?

like image 268
zsharp Avatar asked Feb 17 '09 02:02

zsharp


People also ask

How do I know if AJAX request is successful?

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 { ...

How do I know if AJAX response is true or false?

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 .

How do I know if AJAX request is running jQuery?

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.

How can I get status code from AJAX response?

//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();


2 Answers

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.

like image 71
Jere.Jones Avatar answered Sep 19 '22 05:09

Jere.Jones


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.

like image 25
Matthew Crumley Avatar answered Sep 21 '22 05:09

Matthew Crumley