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

Step-by-step guide: Adding a Google Maps API key to your WordPress theme

Having an issue with Google Maps on my WordPress website. The error message displayed is: Google Maps API error: MissingKeyMapError I have obtained a Google Maps API key, but I am unsure where to insert it. I am not using a Google Maps plugin; instead, my ...

Adjust the dimensions of the dropdown menu

Objective: How can I adjust the width of a select dropdownlist that is utilizing bootstrap v2? Challenge: I am uncertain about how to modify the width in the context of bootstrap. Additional Information: Keep in mind that there are three dropdownli ...

Error message: The Liferay JavaScript Function has not been defined

I am a newcomer to Liferay and have been attempting to utilize Ajax within my scripts, but unfortunately, the code does not seem to load correctly in the browser. I even tried testing it by simply adding an alert. Every time I try, I encounter the "functi ...

Tips for preserving the status of radio buttons in a React application

I am currently utilizing a Map to keep track of the state of radio buttons, but I am facing challenges when it comes to correctly saving and updating it whenever a user makes a selection. The structure of my Map is as follows: { "Group A": [ ...

I am currently struggling with the mapquest GeoJson integration within my Node/Express application. I keep encountering an error message that reads "body used already."

I attempted to utilize the mapquest API by following the provided documentation, however I encountered an error message: HttpError: body used already for: Below is my geoCoder.js configuration: const NodeGeocoder = require('node-geocoder'); con ...

Struggling to make jQuery code function properly in Wordpress, despite attempting to use noConflict

I have created a custom image grid gallery in WordPress using HTML and CSS, complete with popups and sliders. I had to code it myself because I couldn't find a suitable plugin that matched my design preferences. I have tested the functionality on my ...

Using the Composition API in Vue 3: Guide to invoking a method within the template to retrieve a return value

Within my template, I have implemented the following code snippet: <template> {{ getScope(scope.row, itemIn.field) }} </template> For the Option API section, I've included: methods: { getScope(data, key) { const str ...

Receiving errors from Jquery Ajax Calls

I have been attempting to retrieve an AJAX response from the following Twitter URL, but unfortunately, it keeps returning errors. I can't seem to figure out how to make it work. The URL in question is ? I have also tried adding a callback at the end ...

Ensuring that the desired DOM elements have loaded before attempting to manipulate them in Vue.js

I've been struggling with this issue for the past day and I'm completely stuck. In my vue file, there's a method that operates like this: methods: { showSlides(n) { let slides = document.getElementsByClassName("mySlides"); ...

Steps for displaying an HTML table in Excel by clicking on a button

My goal is to open an HTML table in XLS format with a single click of a button. Currently, I have a JavaScript function that allows me to export the HTML table to XLS using the "save as" option. However, I want to enhance this functionality so that clickin ...

Getting Your Redux Form Ready for Submission

I recently transformed my Redux form into a wizard with multiple subcomponents following the structure outlined here: However, I'm encountering difficulties when trying to integrate the form with my actions to submit the form data. Unlike the example ...

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) ...

Extracting values from URL query parameters in Vue.js

When dealing with Vue.js callback URLs, I encounter situations where I need to extract a parameter value from the URL. For instance, consider this return URL: http://localhost:8080/#/sucesspage?encryteddata=abdeshfkkilkalidfel&9a I attempted to retrie ...

Determine the worth of various object attributes and delete them from the list

Currently, my dataset is structured like this: { roof: 'black', door: 'white', windows: 8 }, { roof: 'red', door: 'green', windows: 2 }, { roof: 'black', door: 'green', windows: ...

What could be causing res.redirect to fail at redirecting the page in a nodejs application?

Why isn't the code res.redirect('/taskswriter') working and not directing to the page? Here is the Express.js code snippet: router.route('/update-sources').get(function(req, res) { User.updateMany({"Addtasks.commonID":req.query ...

A stationary webpage nested within a lively pathway on NuxtJS

I have a Nuxt app with a list of cars available at: /cars. You can select a specific car at /cars/:id. I would like to have a toolbar that routes to different views such as: /cars/:id/routes, /cars/:id/drivers, etc. Within the /cars/:id page, I have creat ...

What can be done to address the issue of v-model select option onchange displaying the previously selected value or becoming stuck on a static value rather than updating

Whenever I navigate to the message page and select a device, the v-model selected value changes. However, if I go to the device or contact page, the v-model selected value remains unchanged or goes back to the last selected value. Below is the function in ...

elements on the page that automatically update using AJAX

On my webpage, there is a news slider that displays items one by one. The page automatically refreshes to show new items. I am working on using ajax and a jquery timer to update the page whenever a new item is added. I'm trying to use AJAX to retriev ...

How to Conceal the <th> Tag with JavaScript

I attempted to conceal certain table elements using JavaScript. For <td> elements, it works fine: function hide(){ var x=document.getElementsByTagName('td'); for(var i in x){ x[i].style.visibility='hidden'; ...

Having trouble grasping the problem with the connection

While I have worked with this type of binding (using knockout.js) in the past without any issues, a new problem has come up today. Specifically: I have a complex view model that consists of "parts" based on a certain process parameter. Although the entire ...