Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Ajax beforeSend and success,error & complete

I have a problem with multiple ajax functions where the beforeSend of the second ajax post is executed before the complete function of the first ajax.

The loading class I am adding to the placeholder before sending is working for the first ajax call. However soon after the first ajax request completes the class is removed and never appends again on the second and further calls (remember recursive calls).

While debugging it shows that the beforeSend function of the second ajax call is called first and the complete function of the first ajax call is called later. Which is obvious, because the return data inserted in the page from the first ajax call starts the second call.

In short it's mixed up. Is there any way this can be sorted out?

The function code is as follows

function AjaxSendForm(url, placeholder, form, append) { var data = $(form).serialize(); append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only $.ajax({     type: 'POST',     url: url,     data: data,     beforeSend: function() {         // setting a timeout         $(placeholder).addClass('loading');     },     success: function(data) {         if (append) {             $(placeholder).append(data);         } else {             $(placeholder).html(data);         }     },     error: function(xhr) { // if error occured         alert("Error occured.please try again");         $(placeholder).append(xhr.statusText + xhr.responseText);         $(placeholder).removeClass('loading');     },     complete: function() {         $(placeholder).removeClass('loading');     },     dataType: 'html' }); } 

And the data contains the following snippet of javascript/jquery which checks and starts another ajax request.

<script type="text/javascript">//<!--  $(document).ready(function() {     $('#restart').val(-1)     $('#ajaxSubmit').click(); }); //--></script> 
like image 938
Rehan Anis Avatar asked Feb 08 '14 16:02

Rehan Anis


People also ask

What is beforeSend Ajax?

The beforeSend function is a pre-request callback function that runs before the request is sent to the server. The beforeSend() function use to set the custom headers and all, it is an Ajax event that triggers before an Ajax request is started.

Why is Ajax success not working?

ajax post method. The reason was my response was not in the JSON format so there was no need for the dataType: 'json' line in the submit method. In my case, the returned response was in text format that's why it was not going to success event. Solution: Remove dataType: 'json' line.

What is success and error in Ajax?

success and Error : A success callback that gets invoked upon successful completion of an Ajax request. A failure callback that gets invoked in case there is any error while making the request.

What is success function Ajax?

What is AJAX success? AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.


2 Answers

Maybe you can try the following :

var i = 0; function AjaxSendForm(url, placeholder, form, append) { var data = $(form).serialize(); append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only $.ajax({     type: 'POST',     url: url,     data: data,     beforeSend: function() {         // setting a timeout         $(placeholder).addClass('loading');         i++;     },     success: function(data) {         if (append) {             $(placeholder).append(data);         } else {             $(placeholder).html(data);         }     },     error: function(xhr) { // if error occured         alert("Error occured.please try again");         $(placeholder).append(xhr.statusText + xhr.responseText);         $(placeholder).removeClass('loading');     },     complete: function() {         i--;         if (i <= 0) {             $(placeholder).removeClass('loading');         }     },     dataType: 'html' }); } 

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

like image 150
Serge K. Avatar answered Oct 07 '22 22:10

Serge K.


It's actually much easier with jQuery's promise API:

$.ajax(             type: "GET",             url: requestURL,         ).then((success) =>             console.dir(success)         ).failure((failureResponse) =>             console.dir(failureResponse)         ) 

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(             type: "GET",             url: @get("url") + "logout",             beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)         ).failure((response) -> console.log "Request was unauthorized" if response.status is 401 
like image 45
user1429980 Avatar answered Oct 07 '22 20:10

user1429980