Which design pattern would be best suited for monitoring the completion of multiple ajax requests?

In my code, I have combined 3 separate ajax calls in one function along with checkAjaxCompletion method to monitor each ajax completion flag.

The current approach involves sending multiple independent ajax calls and using an interval method to continuously check the completion flags. However, I am considering exploring alternative methods instead of relying on intervals.

This is how the code looks like:

function manyAjax() {

   setInterval( function() { checkAjaxCompletion(); } , 200);

   ajax1(); 

   ajax2();

   ajax3();

}

function ajax1() {
   //send ajax request to server and update flag based on success or error
}

function ajax2() {
   //send ajax request to server and update flag based on success or error
}

function ajax3() {
   //send ajax request to server and update flag based on success or error
}

function checkAjaxCompletion() {

   if(ajax1_flag == 1 && ajax2_flag == 1 && ajax3_flag == 1) {
       //all ajax requests completed successfully
   }
   else if(ajax1_flag == 2 || ajax2_flag == 2 || ajax3_flag == 2) {
       //some ajax requests failed
   }
   else {
      //not all ajax requests are completed yet
   }
}

I am concerned about the inefficiency of using the interval function repeatedly and believe there might be a more optimal solution. I am contemplating the use of the observer pattern, but I am open to suggestions and insights from others.

Answer №1

Perhaps you could consider implementing an observer-notifier pattern in your AJAX calls. Each call can have a callback function in JavaScript that gets executed upon completion. Instead of waiting for all calls to finish, try calling checkAjaxCompletion() at the end of each call and handle any necessary actions based on the result.

Answer №2

Dustin Diaz demonstrates an excellent example in his article on the JavaScript observer class.

function Observer() {
  this.fns = [];
}

Observer.prototype = {
  subscribe : function(fn) {
    this.fns.push(fn);
  },

  unsubscribe : function(fn) {
    this.fns = this.fns.filter(
      function(el) {
        if ( el !== fn ) {
          return el;
        }
      }
    );
  },

  fire : function(o, thisObj) {
    var scope = thisObj || window;
    this.fns.forEach(
      function(el) {
        el.call(scope, o);
      }
    );
  }
};

The publisher:

var o = new Observer;
o.fire('here is my data');

The subscriber:

var fn = function() {
  // my callback stuff
};

o.subscribe(fn);

To unsubscribe:

var fn = function() {
  // my callback stuff
};

o.subscribe(fn);

Answer №3

// function for ajax callback
            this.ajaxCallback = function(){                          
                $.ajax({            
                        type: "POST",
                        url: ajax.url,
                        data: {key: value},
                        async   : !isAll,// false for synchronous AJAX request, true for asynchronous AJAX request
                        dataType: "json",
                        success: function(data){
                            if(data.status == 'successful'){                                
                                selfVal.parent().find('.msg').addClass('ok').html(msg.ok);
                            }else if(data.status == 'failed'){
                                checkRet = false;
                                selfVal.parent().find('.msg').removeClass('ok').html(msg.error);
                            }else{
                                checkRet = false;
                            }
                            return this;
                     }
                });                 
            }               
            return this;

If you need to validate the input value and handle the callback using Ajax in your form, you can refer to my website Demo. It might be helpful.

Answer №4

I had an innovative idea to create a custom object capable of managing an array of requests, maintaining a log of each request, and performing what I like to call 'postProcessing' on every response. Below is a somewhat rudimentary code snippet intended to illustrate my concept.

var CustomAjax = function() {
    var request, callback, lst;

    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }

    request.onreadystatechange = handleResponse;

    this.history = [{}];

    this.send = function(args) {
        for (var i = 0; i < args.length; i++) {
            if (args.url) {
                request.open(args.type || 'GET', args.url);
            }
            request.send(args.data || null);
            callback = args.callback;
            lst++;
        }
    }

    function handleResponse() {
        var response = {
            url: '',
            success: true,
            data: 'blah'
        };
        history.push(response);
        if (postProcess()) {
            callback();
        }

    }

    function postProcess() {
        if (this.history[lst].success) {
            return true;
        } else {
            return false;
        }
    }
}

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

Module 'js' not found

Upon adding a request, I encountered this error message. I attempted npm install js and added var js = require("js") in my app.js file, but unfortunately it did not resolve the issue. My express server is running on localhost. Error: Cannot find module &a ...

Attempting to configure a discord bot. Can anyone help me identify the issue?

I've been working on setting up a discord bot using Discord.js. I have all the necessary tools installed - Node.js, Discord.js, and Visual Studio Code. I've even created an application and obtained a token for my bot. However, I'm running in ...

Unleashing the Power of Dynamic JSON Data Access

I am facing an issue with my React Child component. Here is the code snippet: const SingleProject =(props)=>{ let data = projectData.VARIABLE_FROM_PROPS.projectDetails; let asideData = projectData.VARIABLE_FROM_PROPS.projectSideBar; useEffe ...

Ensure all fields are valid prior to performing an update

I'm currently faced with the challenge of validating my form data before executing an AJAX update. Essentially, what I want to achieve is to validate the input data in the form before triggering the ajax update function. I'm unsure about where to ...

The response is dispatched without delay and does not necessitate awaiting

I am facing an issue with waiting for the completion of the getAllData function before proceeding further. let _partnerToken; async function getAllData(dealerId,id){ let partnerToken; var options = { 'method': 'GET', ' ...

Replacing an array element by a specific index number in a React application

I am dealing with an array of [false,true,false,false,true] and I am looking to update the boolean values based on their index numbers. I have been trying to solve this problem in react, but haven't found a workable solution yet. this.setState({ ...

What is the best way to handle requests once a SpookyJS script has finished running?

Occasionally, I find myself needing to log in and extract some data from a specific website. To automate this process, I developed a CasperJS script that runs on Heroku. My goal is to create an endpoint like the following: app.get('/test', func ...

The text-center alignment in Bootstrap doesn't seem to be applying to buttons

After spending a considerable amount of time trying to center two buttons in Bootstrap, I came across the "text-center" class offered by Bootstrap. However, no matter where I include this class, it doesn't seem to have any effect on the alignment of t ...

Ways to delete a particular query parameter from a URL in Next.js

http://localhost:3000/?search=test&type=abc&category=xyz When searching for "test" along with the type and category, the URL changes accordingly to the link provided above. return router.push( { pathname: `/`, query: { ...

What is the best way to mimic an AJAX request using the Flask test client?

When testing Flask applications, the process involves: # main.py from flask import Flask, request app = flask.Flask(__name__) @app.route('/') def index(): s = 'Hello world!', 'AJAX Request: {0}'.format(request.is_xhr) ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

Is it possible to improve the cleanliness of a dynamic button in Jquery?

I've just finished creating a dynamic button on the screen as per my boss's request. When this button is clicked, it triggers an email window for feedback submission. My aim is to streamline this script so that I can avoid digging into ASP marku ...

Controller encounters a error when requiring a module

Struggling to set up Stripe for my app, I've encountered some issues with the module implementation. Typically, I would require a module at the top of the file to use it. However, in the paymentCtrl file, when I do this, it doesn't work and I rec ...

Retrieving Database Data using Ajax Cascading DropDownMenus

This project marks my first experience with Ajax and C#.NET. As a newcomer using .NET 4.0, I have successfully integrated a cascading dropdown feature that stores data in the database upon submission. However, I have encountered a roadblock when it comes t ...

Having trouble with your HTML5 canvas?

Below is the JS code snippet: function DisplayText(output, x, y){ var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillText ("A" , x, y); ctx.font = 'bold 20px sans-serif'; ...

Leverage the exported data from Highcharts Editor to create a fresh React chart

I am currently working on implementing the following workflow Create a chart using the Highcharts Editor tool Export the JSON object from the Editor that represents the chart Utilize the exported JSON to render a new chart After creating a chart through ...

Tips for detecting a false return value from a jQuery AJAX script

I am currently utilizing jQuery and AJAX to perform form validation when a new user is being created on my website. My development environment consists of OOP PHP in conjunction with jQuery and AJAX. Here is the code snippet I am using: $.ajax({ ...

Dynamically update the contents of a ModalPopup using AJAX when controls within the panel are changed

I'm facing a challenge with an AJAX Modal Popup panel that contains a RadioButtonList, 2 labels, and 2 DropDowns. I need to update the Labels and DropDowns when a radio button is selected. However, my current approach triggers a postback which causes ...

Troubleshooting the Hover Effect of Buttons in Next.js when Using Tailwind CSS for Dynamic Color Changes

Encountering a problem with button hover functionality in a Next.js component using Tailwind CSS. The objective is to alter the button's background color dynamically on hover based on a color value stored in the component's state. This code func ...

Using an array as a reference can lead to failure when dealing with asynchronous calls

As I delve into referencing a document in MongoDB, my process involves first creating the document to insert before interfacing with the database itself. Upon initial setup: const venues = [ new Venue({ name: 'A' }), ]; const events = [ new ...