Tips for optimizing the sequencing of 3 ajax requests, with the output of one request serving as input for the subsequent two requests

I'm currently working on a solution for chaining 3 ajax calls where the result of one call feeds into the next two. Here's the scenario:


// Invoke the ajax calls
firstAjax('mypage.gng','john-doe').then(secondAjax, thirdAjax).done(function(second_ajax_data, third_ajax-data) {
        console.log(second_ajax_data);
        console.log(third_ajax-data);
});

// Define our ajax calls

const firstAjax = function(urlAjax, userName) {

      return $.ajax({
              url: urlAjax,
              type: 'POST',
              data: userName
             )};

const secondAjax = function(sessionId) {

       return $.ajax({
              url: '/userLogins/getUserLogins',
              type: 'POST',
              data: sessionId
             )};

const thirdAjax = function(sessionId) {

       return $.ajax({
              url: '/userHistory/getUserHistory',
              type: 'POST',
              data: sessionId
             )};

Essentially, the firstAjax call fetches the sessionId and then passes it to the other 2 ajax calls simultaneously. However, I'm facing issues in obtaining the data returned by the last two calls using the above setup. I would really appreciate any assistance.

Answer №1

Perhaps a solution along these lines could be effective:

function send_ajax_request(data){
    $.ajax({
      url: "yoururl",
      type: "GET",
      dataType: "json",
      data: {
        data: data,
        csrfmiddlewaretoken: '{{ csrf_token }}'
      },
      success: function (json) {
        next_ajax(json['success']);

      },
      error: function (xhr, errmsg, err) {
        alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
      }
    });

}

function next_ajax(data){
$.ajax({
    url: "yoururl",
    type: "GET",
    dataType: "json",
    data: {
      coord: JSON.stringify({ "info": data[0], "info2": data[1] }),
      csrfmiddlewaretoken: '{{ csrf_token }}'
    },
    success: function (json) {
      console.log(json)

    },
    error: function (xhr, errmsg, err) {
      alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
    }
  });

}

To put it simply, utilize the success function of your Ajax call to trigger the subsequent Ajax request. It's worth a shot!

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

Error encountered: JSHint is flagging issues with setting a background gradient using

I have been experimenting with animating a background gradient using jQuery, and here is the code snippet I am working with: this.$next.css('line-indent', 0).animate({ 'line-indent': 100 }, { "duration": 750, "step": functi ...

Unraveling the mysteries of an undefined entity

When the variable response is undefined, attempting to retrieve its property status will result in an error: Error: Unable to access property 'status' of undefined const { response, response: { status }, request, config, } = error as A ...

The function setCustomValidity() will continue to display even after the form has been successfully filled out

My form is very simple and I am trying to validate it using the required attribute: <form name="form"> <label for="Header">Title</label> <input type="text" class="span5" name="Header" ng-model="Message.header" placeholder="Title" on ...

Working with dynamic checkbox values in VueJS 2

In my project using VueJS 2 and Vuetify, I am creating a subscription form. The form is dynamic and fetches all the preferences related to a subscription from the server. In the example below, the preferences shown are specifically for a digital magazine s ...

Failure to retrieve JSON using $.ajax in JSP

I am attempting to retrieve a JSON Array from a Servlet and populate data into a table. However, the JSON or text is not being received in the JSP despite trying various methods. Below is my JSP code: <%@ page contentType="text/html;charset=UTF-8" lan ...

Update the canvas box's color when you interact with it by clicking inside

I'm in the process of developing a reservation system and I'm looking to implement a feature where the color of a Canvas changes when clicked. The goal is for the color to change back to its original state when clicked again. Snippet from my res ...

Utilize a singular object to contain multiple instances of the useState hook

const [regionData, setRegionData] = useState({ country: "", city: "", population: "", location: "", temp_min: "" }); Does anyone know a more efficient and cleaner way to replace these individual useState hooks by organizing them into ...

How to achieve padding of strings in JavaScript or jQuery

Does anyone have information on a similar function in jQuery or JavaScript that mimics the prototype toPaddedString method? ...

Retrieve a markdown file from the system and render it as a string using React.js

Is there a way to load a markdown file from the current directory as a string in my code? This is the scenario: import { State } from "markup-it" ; import markdown from "markup-it/lib/markdown"; import bio from './Bio.md' const m ...

When attempting to use nodejs's collection.find() method with MongoDB, no response is received

I have been struggling to develop a node.js script that can retrieve only the records with a specific string key-value pair from a MongoDB collection containing around 30,000 documents. When I run this query on my MongoDB server, it gives me the exact res ...

Improved method for categorizing items within an Array

Currently working on developing a CRUD API for a post-processing tool that deals with data structured like: { _date: '3/19/2021', monitor: 'metric1', project: 'bluejays', id1: 'test-pmon-2', voltageConditio ...

Guide to making a slider menu using html, css, and javascript

Just dipping my toes into the world of web development. I'm intrigued by the idea of creating a "slider menu" where users can view and select options by clicking on next or previous buttons (see example image below). While I've got some basic HTM ...

Repeatedly Triggered JQuery AJAX Calls

On my web page, I have implemented a feature that allows users to search for an address using a GIS server's web-service. This functionality is triggered by a button click event which calls a JQuery AJAX method. Upon successful retrieval of address da ...

Utilizing the GData API for seamless integration with cross-domain ajax requests

I need to retrieve XML data from Google's server using its API. I am unable to modify the response, so how can I make this call work for me: $.ajax({ type: 'POST', url: 'https://www.google.com/accounts/ClientLogin', ...

Avoiding the duplication of selected items in a dropdown within a gridview can be achieved effectively by implementing a JavaScript/jQuery

In my gridview, which contains multiple rows, each row has a dropdown (select in HTML). My goal is to prevent the user from selecting the same item from the dropdown list for different rows. For instance, if a user selects "New York": Assigning rooms: U ...

React Component Div Containing a Hydration Error

Can someone help me resolve the Hydration error related to a nested div issue? I am working on a component that has two main functions - fetching data and mapping it. However, I keep encountering a hydration error and I'm not sure why it's happe ...

Comparing two Objects in JavaScript results in automatic updates for the second Object when changes are made to the first

Can someone please assist me with a hash map issue I'm encountering in my for loop? When resetting the second object, it unintentionally alters the Map values of the previous Key in the Hash Map. Any guidance on how to prevent this behavior would be g ...

What steps can I take to troubleshoot and fix the height of a div/span element?

Here is my HTML code: <div> <span style="display: inline-block;height:20px">20</span> <span style="display: inline-block;"><img src="img/ex.png"/></span> </div> The image I have in the second span is sized at ...

Troubleshooting: Success with AJAX call in Chrome, but issues in IE

Having issues retrieving JSON data from a URL that displays the last 3 numbers of a webpage. The AJAX call functions correctly in Google Chrome but fails in Internet Explorer. I tried disabling caching using cache: false as suggested, but the problem persi ...

"Integrating multiple partials with templateUrl in AngularJS: A step-by-step

Is there a way to merge partial views using the templateUrl attribute in an AngularJS directive? Imagine having a directive like this: .directive('combinePartials', function () { var mainPartial = "mainpartial.html", var template2 = "pa ...