Utilizing Jquery queue for running a series of Ajax requests; imperative to clear the queue in case of a failed request

I am currently working on creating a queue of ajax calls that need to be executed in order. The process seems to be functioning properly, but I am encountering an issue when there is an error in one of the calls. My goal is to stop the queue after an error occurs so that the remaining ajax calls are not executed.

As someone who is new to the concept of jquery queues, I came across this code online for extending jQuery:

var ajaxQueue = $({});

(function($) {

    $.ajaxQueue = function(ajaxOpts) {

        // keep track of the original complete function
        var oldComplete = ajaxOpts.complete;

        // queue our ajax request
        ajaxQueue.queue(function(next) {    

            // create a complete callback to trigger the next event in the queue
            ajaxOpts.complete = function() {
                // trigger the original complete if it existed
                if (oldComplete) oldComplete.apply(this, arguments);    
                next(); // run the next query in the queue
            };

            // execute the query
            $.ajax(ajaxOpts);
        });
    };

    // I also added this in an attempt to clear the queue
    $.clearQueue = function(ajaxQueue) {
        ajaxQueue.clearQueue();
        ajaxQueue.stop();
    };

})(jQuery);

Then, I have a function to add an item to the queue:

function queueAjax( passObj, success, ajaxQueue ) {

    $.ajaxQueue({
        url: route() + 'global_fxns/ajaxHub',
        async: true,
        data: {'passme' : encodeURIComponent( JSON.stringify( passObj ) ) },
        success: function(data) {

            var aJSON = decodeURIComponent(data);       
            var retObj = $.parseJSON(aJSON);    

            // if there were no issues, call the specified success function
            success( passObj, retObj );                    

        },
        error: function ( jqXHR, textStatus, errorThrown) {
            clog("error");

            // trying to clear the queue if there's an error        
            ajaxQueue = $({});
            $.clearQueue(ajaxQueue);
        } 
    });

Finally, to make a call to queueAjax:

    var arr = standardAjaxArray( "testQueue", 0 );
    var obj1 = { 
        arr: arr,
        count: 1
    };
    function success( passObj, retObj, ajaxQueue ) {
        clog("Queue success!");
    }
    queueAjax( obj1, success );

The challenge I'm facing is that no matter what I try, I am unable to empty the queue if there's an error in the ajax call. Even when intentionally introducing an error on the backend and calling queueAjax multiple times, it runs every time. I've attempted extending jQuery with $.clearQueue and passing the queue as a parameter with no success. Any advice or suggestions would be greatly appreciated. Thank you!

Answer №1

After some troubleshooting, I managed to figure it out. It turns out that the issue was with the $.clearQueue definition. By removing ajaxQueue = $({}) before calling ajaxQueue.clearQueue(), the problem was solved. It seems that by assigning ajaxQueue = $({}), which was meant to clear the queue, I was actually just reassigning the variable without emptying it. This resulted in no effect when calling .clearQueue().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the failure of this click binding to get bound?

Take a look at this fiddle: http://jsfiddle.net/BxvVp/11/ I have created a view model with a function that replaces the content of a div with some hidden content on the page. After this replacement, the text binding seems to work fine, but the click bindi ...

Ways to automatically refresh the div block's content whenever new data is added or updated in the database

Is there a way to automatically refresh the div block whenever there is activity in the database? I attempted using the setInterval function, but I'm looking for a solution that will update or insert data into the block based on updates made to the da ...

How to eliminate spaces while preserving line breaks in a textarea using JS or jQuery

I have been trying to figure out how to remove extra spaces from the beginning and end of lines while keeping the line breaks intact. Here's what I attempted: function removeSpaces(string) { return string.split(' ').join(''); } ...

Conclusion of Tour when an event is triggered by the parent view - Intro.js

File Manager - Home Normal https://i.stack.imgur.com/7C5lH.png I primarily utilize AJAX callbacks for most of my content. Whenever I click a link button on the page, it triggers a modal pop-up using jQuery events and a specific class. The Tour Guide implem ...

How can I prevent Sundays from being selected in a jQuery datetimepicker?

I'm currently working with a jquery datetimepicker and my goal is to exclude Sundays from the selection. How can I achieve this? Below is the jquery code that I am using: $(".datetimepicker").datetimepicker({ format: 'm-d-Y H:i', defaultD ...

What should a Laravel controller return in response to an ajax request?

I encountered an issue in handling the response for an ajax request I initiated. Essentially, when a checkbox is changed(), it triggers an ajax call with a csrf-token that needs to be accepted via the POST method. The modifications are successfully made i ...

Step-by-step guide on how to load an Ext JS tab after clicking on it

I have an Ext JS code block that creates 4 tabs with Javascript: var tabs; $(document).ready( function() { fullscreen: true, renderTo: 'tabs1', width:900, activeTab: 0, frame:true, ...

What's causing this error with jQuery and JSON?

When utilizing the following code snippet: - $.getJSON("admin.php?format=json", { module: "data", action: "allBusinessUnitsByClientName", clientname : $('#client').val() }, function(json) { $.each(json.items, function(i,item){ alert ...

Capturing scroll events just once

I am working on implementing scroll events to create a smooth "snapping" effect for the top sections of my webpage. While I have successfully captured and animated the scroll position, I am encountering an issue where the scroll event is being triggered mu ...

Interactions in JQuery UI

Having issues with jQuery UI events. I have sliders in my app and occasionally need to adjust the "min" option. However, I'm facing a problem where the change() event is not triggered after making the adjustment. I would assume that every time the val ...

The jQuery Ajax call triggers a page refresh

I've searched high and low for a solution, but I just can't seem to figure it out. I have a simple jQuery code snippet below that successfully retrieves the IDs (array) of checkboxes and sends them to the report.php page using Ajax: $('#repo ...

Having trouble parsing JSON data from $_POST while utilizing AngularJS

While working in Angular, I encountered the following scenario: var data = {}; data['name'] = "test"; data['class'] = "testClass"; $http.post('http://testURL',data,function(data){ console.log(data); }); Upon inspecting the ...

Perform Action Only When Clicking "X" Button on JQuery Dialog

I have a dialog box with two buttons, "Yes" and "No", which trigger different functions when clicked. $('#divDialog').dialog({ modal:true, width:450, resizable: false, buttons: [{ text: 'Yes', ...

Photo displayed above the carousel using Bootstrap

I'm currently in the process of building a website using the template found at . However, I'm having trouble placing an image in the center of the carousel, above the slides. Here is the code snippet I have tried so far: <div style="positi ...

WooPay Multi-Currency Integration with Dynamic AJAX Technology

Currently, I have implemented WooPayments Multi-Currency to enable currency changes. It is working perfectly except when loading products through AJAX, as they continue to display in the default currency. Is there a solution to make these products appear ...

The JavaScript code will automatically execute loops

Let me illustrate my point with two functions. Function 1 This function triggers a transition when you hover over the square. If you move your mouse off the element and then back on while the transition is still in progress, it will wait until the end of ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Is it possible to transmit information to a PHP script using jQuery's post function without triggering a page reload?

I am working on a form submission that needs to happen without refreshing the page. The objective is to receive the form data and manipulate it within the same page. The form's purpose is to add a new row in the clients table, and I need to retrieve ...

How can I choose an element based on its specific class using jQuery?

I've written some jQuery code that looks like this: jQuery(document).ready(function($){ $(".lmls").click(function(){ var groupid = $('span#gid').attr('value'); $("#otherpaths"+groupid).toggle(); // aler ...

The div with a 'inline-block' display and maximum width appears to be wider than needed after a line break

The red div labeled as inline-block-1 in the jsFiddle takes up more space than needed for the text. Is there a way to eliminate the extra space, making it resemble the green inline-block-2 without removing the max-width and avoiding hard-coding width? Feel ...