Optimal method for linking jQuery ajax requests to transfer data

Handling several asynchronous ajax calls in a specific order with information passing between them can be quite challenging. The current approach, even with just three API calls, can be cumbersome. Trying to manage five API calls makes it nearly impossible to organize the error workflow or adjust functions effectively due to limited screen space. Is there a more efficient way to achieve the desired outcome?

/*
 * API Call to get user
 */
$.ajax({
    type: 'POST',
    url: `robin.hood/get_user`,
    data: JSON.stringify({"name":"Joe Dirt"}),
    headers: {Authorization: 'Bearer ' + token},
    datatype: 'json',
    contentType: 'application/json; charset=utf-8',
    success: function (data, text_status, jq_xhr) {
        /*
         * Assume one user is returned only
         */
        let user_id = data;

          // Additional nested AJAX calls and operations...
                    
});

For similar questions:

  1. Chaining multiple jQuery ajax requests
  2. jquery how to use multiple ajax calls one after the end of the other

Answer №1

When using $.ajax, it returns a Thenable object. This allows you to use the await keyword inside an async function, making it easier to handle and manage compared to using nested callbacks:

async function run() {
  try {
    const user = await $.ajax({
      type: 'POST',
      url: `robin.hood/get_user`,
      data: JSON.stringify({
        "name": "Joe Dirt"
      }),
      headers: {
        Authorization: 'Bearer ' + token
      },
      datatype: 'json',
      contentType: 'application/json; charset=utf-8',
    })

    const balance = await $.ajax({
      // ...
    })

    const data = await $.ajax({
      // ...
    })

    /* STONKS!!! */
  } catch (e) {
    /* NO STONKS */
  }
}
run()

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 is the best way to format a condensed script into a single line?

There are times when the script in the web browser is packed into one line like function a(b){if(c==1){}else{}}. I have attempted to locate something that would display it in a more normal format. function a(b) { if(c==1) { } else { } } Howev ...

Use JavaScript to add a div element to the page ten times every time the button is clicked

Here is the code I have written: $(document).ready(function () { $('<button class="btn more">View More</button>') .appendTo(".listing-item-container") .click(function() { $(this).closest(". ...

The issue with element.style.backgroundColor not functioning properly within WordPress

Struggling to make the background of a button change upon hover? I've got the code, but it seems to be working everywhere except in WordPress. Check out the code that should be working here: https://jsfiddle.net/TopoX84/3oqgmjb0/ Want to see it not ...

The feature of Google street view is not supported within the tabs on WordPress

I'm experiencing some issues with displaying Google maps and street view using the Wp Google Map WordPress plugin within tabs. The map displays perfectly on the first tab where I placed the short code for the map, but on the second tab where I placed ...

Search for a div element in jQuery that has a specific data attribute

Hey there, I'm currently working with the following HTML: <div class="yay" data-pi="23"></div> <div class="yay" data-pi="24"></div> <div class="yay" data-pi="25"></div> <div class="yay" data-pi="26"></div& ...

How can one effectively capture and handle Ajax errors on a global scale in an ASP.NET MVC application?

Often I catch myself adding this (simplified) code in multiple javascript files: $(document).ajaxError(function (e, xhr, settings, exception) { alert('error in: ' + settings.url + ' \\n' + ...

Instructions on how to create a horizontal scrolling div using the mouse scroll wheel

I need help with scrolling a div horizontally using the mouse scroll button. My div does not have a vertical scroll and I would like users to be able to scroll horizontally. Can anyone provide guidance on how to achieve this? ...

What is the best way to open the index.html file in electron?

I'm currently developing a cross-platform app using electron and Angular. As of now, the code I have for loading my index.html file looks like this: exports.window = function window() { this.createWindow = (theBrowserWindow) => { // Create ...

real-time synchronization between database changes and web page updates

Currently experiencing some issues while working on a website with a chat feature. We were successful in updating the message display area when a user submits a message. However, we encountered a problem where the chat would start reloading continuously ...

Utilize Discord.js to send a message and patiently await your response

I am facing an issue while trying to code a Discord bot. I'm struggling to make it wait until the user inputs 'Y' or 'N'. Specifically, I am currently working on the ban command and everything seems to be functioning well until the ...

Troubleshooting Ajax POST issues with Laravel

Looking for a way to submit a form with checkboxes representing user interests? Clicking a checkbox will send the checked interest value to the database "Followers" table, allowing the user to start following that interest. To handle this, I decided to cre ...

Populate the AngularJS scope with a dynamically generated array

My Angular Application is functioning properly with <script> var app = angular.module('MyApp', []); app.controller('myCtrl', function ($scope, $sce) { $scope.urls = [ { "url": $sce.t ...

What do you want to know about Angular JS $http request?

My goal is to send a request using $http with angular js in order to retrieve a json object from google maps. $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city&a ...

DNN backend method not being triggered by JQuery Ajax function

I am facing an issue with DotNetNuke where the backend code is not executing from my JQuery Ajax function. Below is the JQuery code snippet present in my View.ascx file: Despite changing the URL to View.ascx/DeleteReviewData, I am still unable to resolve ...

Is it true that Safari restricts AJAX Requests following a form submission?

I've developed a JavaScript-based upload progress meter that utilizes the standard multipart submit method instead of submitting files in an iframe. The process involves sending AJAX requests during submission to retrieve the percentage complete of th ...

Unread elements

I have generated a dynamic list of pages using JSON and have displayed them in a . However, the elements created by the for loop do not seem to be accessible to JavaScript or CSS. For instance, the links within the for loop should be converted into buttons ...

Problem with using puppeteer to interact with a dropdown menu

I have a project in which I am utilizing puppeteer to create a bot that can automatically check for my college homework assignments. The problem I am encountering is that when the bot tries to click on a dropdown menu, it fails and I receive an error messa ...

Unable to select the initial element

Having trouble targeting the first child in this code snippet. I've tried various methods but nothing seems to be working. Any suggestions on how to resolve this? <div id="main"> <div class="page"> <p>random 1</p> </div ...

Using PHP's $_GET with an Ajax/Jquery Request

I've been struggling to set a variable $id=$_GET["categoryID"] and can't seem to make it work. I suspect it's related to the Ajax request, but I'm unsure how to format it correctly to work with the request for my mysql query. Any assist ...

Is Jquery Steps causing interference with the datepicker functionality?

I am currently using the jquery steps plugin for creating a wizard on my website. However, I am experiencing some issues with the functionality of the datepicker and qtip inside the steps. Even after switching the .js references, the problem still persists ...