Imagine we have this code and we are calling it again and again but this code takes some time to get response from server, now we dont want overwhelm our server with too many pending requests so how we can cacnel pending requests and fire a fresh request

 


function getAllDemographicData(){
            var csrfToken = $('meta[name="csrf-token"]').attr("content");

            $.ajax({
                url: '/admin/data-report/get-all-demographic-data/',
                type: 'POST',
                data: {
                    formData: formData,
                    _token: csrfToken,
                },
                success: function(response) {
                    console.log(response);
                    if(response.demographicDataField){
                        // upate demographic fields 
                        console.log("here is demographic data",response.demographicDataField);
                        pushDynamicFieldsData(response.demographicDataField);
                    }
                    
                },
                error: function(xhr, status, error) {
                    // Handle the error
                    
                }
            });
        }

To cancel the previous AJAX request if the function gets called again without waiting for the previous function to finish, you can store the previous request object in a variable, and abort it when the function is called again. Here’s the updated version of your function that includes this logic:

 

var previousRequest = null;

function getAllDemographicData() {
    // If there is an existing AJAX request, cancel it
    if (previousRequest) {
        previousRequest.abort();
        previousRequest = null;
    }

    var csrfToken = $('meta[name="csrf-token"]').attr("content");

    previousRequest = $.ajax({
        url: '/admin/data-report/get-all-demographic-data/',
        type: 'POST',
        data: {
            formData: formData,
            _token: csrfToken,
        },
        success: function(response) {
            console.log(response);
            if (response.demographicDataField) {
                // update demographic fields
                console.log("here is demographic data", response.demographicDataField);
                pushDynamicFieldsData(response.demographicDataField);
            }
        },
        error: function(xhr, status, error) {
            // Handle the error
            // Only handle the error if the request was not aborted
            if (status !== 'abort') {
                console.error("An error occurred:", error);
            }
        },
        complete: function() {
            // Clear the previousRequest variable when the request completes
            previousRequest = null;
        }
    });
}


 

Here’s the breakdown of what this code is doing:

  1. var previousRequest = null;: This variable is used to store the current AJAX request object. It’s defined outside of the function so that it persists across multiple calls to getAllDemographicData.
  2. if (previousRequest) { ... }: Before we make a new AJAX request, we check if previousRequest contains an existing request. If it does, we call the abort() method on that request object, which cancels the previous AJAX request.
  3. previousRequest = $.ajax({...});: We store the current AJAX request object in the previousRequest variable. This allows us to cancel it if getAllDemographicData gets called again before this request finishes.
  4. error: function(xhr, status, error) {...}: In the error callback, we check if (status !== 'abort') { ... }. This is to ensure we only handle genuine errors and not the errors triggered by aborting a request.
  5. complete: function() {...}: In the complete callback, we set previousRequest back to null. This ensures that, once the request is completed (whether successfully or with an error), we don’t hold a reference to it anymore.

Now, when getAllDemographicData is called again while a previous request is still pending, the previous request will be aborted, and a new request will be started.

#ajaxcancel #ajaxcallcontinously #ajax #laraveajax

Don’t miss these tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

By CLTK

Leave a Reply

Your email address will not be published. Required fields are marked *