Does the first Ajax call always finish first in the order of Ajax calls?

In my code, I have an ajax call that triggers another ajax call based on its return value. The URL parameter of the second call is modified by the output of the first one. These two calls are interrelated as the first call feeds the URL parameter for the second call. The output of the second call is then appended to a global variable, which is used to generate a final HTML set that is further appended in the first call. Here's a simplified example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var masterHtml = '';

// First Ajax Call
$.ajax({
    url: "http://thisisanexample/items",
    type: "GET",
    asynch: false,
    contentType: "application/json;odata=verbose",
    headers: {
        "Accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function(data) {
        successHandler(data);
    },
    error: function(data) {

    }
});

function successHandler(data) {
    var results = data.d.results;
    for (var i = 0; i < results.length; i++) {
        var someHtml = results[i]["someHtml"];
        masterHtml = masterHtml + someHtml;
        var nextThingUrl = results[i]["nextThingUrl"];

        // Second Ajax Call
        $.ajax({
            url: "http://thisisanexample/+ " + nextThingUrl,
            type: "GET",
            asynch: false,
            contentType: "application/json;odata=verbose",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function(data) {
                successHandlerChildren(data);
            },
            error: function(data) {

            }
        });
        jQuery('#magictime').append(masterHtml);
    }
}

function successHandlerChildren(data) {
    var results = data.d.results;
    for (var i = 0; i < results.length; i++) {
        var someMoreHtml = results[i]["someMoreHtml"];
        masterHtml = masterHtml + someMoreHtml;
    }
}

The issue I'm facing is that the first ajax call always completes before the second call is made, resulting in the incorrect order of operations. The first call provides the initial HTML while the second call provides additional HTML needed. What am I overlooking? Any help would be greatly appreciated! Thanks in advance!

Answer №1

The spelling of the async option is incorrect, please use:

async: false

Answer №2

Seems like you're attaching your data prematurely. You should relocate

jQuery('#magictime').append(masterHtml);
within the
function successHandlerChildren(data)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var masterHtml = '';

$.ajax({
url: "http://thisisanexample/items",
type: "GET",
asynch: false,
contentType: "application/json;odata=verbose",
headers: {
    "Accept": "application/json;odata=verbose",
    "X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
    successHandler(data);
},
error: function (data) {

}
});

function successHandler(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
    var someHtml = results[i]["someHtml"];
    masterHtml = masterHtml + someHtml;
    var nextThingUrl = results[i]["nextThingUrl"];
    
    $.ajax({
        url: "http://thisisanexample/+ " + nextThingUrl,
        type: "GET",
        asynch: false,
        contentType: "application/json;odata=verbose",
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            successHandlerChildren(data);
        },
        error: function (data) {

        }
    });
}
}

function successHandlerChildren(data) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
    var someMoreHtml = results[i]["someMoreHtml"];
    masterHtml = masterHtml + someMoreHtml;
}
jQuery('#magictime').append(masterHtml);
}

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

The Minimax algorithm experiencing issues in Next.js

I recently wrote some code in Next.js, but unfortunately, it's not functioning as expected. Despite my best efforts and attempts at utilizing alpha beta pruning, the code still fails to work properly. The issue lies in the fact that it simply returns ...

The arrow function in Jest is missing a name property

Currently, my setup includes: node.js: 9.8.0 Jest: 23.4.2 ts-jest: 23.1.3 typescript: 2.9.2 While attempting the following in my *.test.ts files: const foo = () => 'bar'; console.log(foo.name); // '' foo contains the name pro ...

What is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...

Transform your data visualization with Highcharts enhanced with the stylish appearance of DHTML

I am currently using a dhtmlx menu with my charts, specifically the legendItemClick event. It worked perfectly when I was using highcharts 3.0.1. However, after upgrading to version 4.1.7, the function legendMenu_<?=$id?>.showContextMenu(x,y) in the ...

Having difficulty resolving all parameters for the component: (?, [object Object]) in the Jasmine component Unit Test

While defining a UT for a component with an extended class using i8nService and ChangeDetectionRef, I encountered an error preventing me from instantiating it: Failed: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object] ...

Passing all selected items from a list to the controller

I am currently facing an issue with my two multi-select lists. One list contains a full list of names while the second one holds the names that have been selected from the first list. The names are stored in a Vue array which populates the names into the s ...

JavaScript event/Rails app encounters surprising outcome

I have encountered a strange bug in my JavaScript code. When I translate the page to another language by clicking on "English | Русский" using simple I18n translation, my menu buttons stop working until I reload the page. I suspect that the issue ...

What happens when arithmetic operators are applied to infinity values in JavaScript?

Why do Arithmetic Operators Behave Differently with Infinity in JavaScript? console.log(1.7976931348623157E+10308 + 1.7976931348623157E+10308)//Infinity console.log(1.7976931348623157E+10308 * 1.7976931348623157E+10308)//Infinity console.log(1.797693134 ...

Having trouble with importing a variable in an Express application? You may encounter this error message: "Route.get() must

When trying to import requireSignin from the controllers/auth.js file into the routes/user.js file and adding it to the router.get('/user/:id', requireSignin, read); route, an error occurs: Error: Route.get() requires a callback function but r ...

Creating a Dynamic Dependent Dropdown with Jquery and Ajax in PHP

As a newbie in coding, I stumbled upon some valuable information to enhance my register form using Ajax. While the PHP files seem to be functioning correctly, I suspect that the JS file is not performing as expected. In the register form, you'll find ...

I updated the script to include a feature that automatically adds a leading zero to hours, minutes, and seconds if they are less than 10. However, for some reason, the output still doesn't show the leading zero

I have successfully created a countdown timer that works effectively. One of the conditions I added is to display leading zeros for hours, minutes, and seconds if they are less than 10. The desired format is like this (06 : 08 : 09) instead of (6 : 8 : 9 ...

The jQuery selector is unable to detect the Bootstrap modal when it is hidden

I attempted to change the value of a jQuery selector within a bootstrap modal, but unfortunately, my efforts were unsuccessful. Even after utilizing the Chrome console, I was unable to modify the value as intended. Could someone offer guidance on how to re ...

I am seeking guidance on creating a dynamic search feature using node.js and mongoDb. Any input regarding

I am currently working on implementing a unique feature that involves having an input field on this specific page. This input allows users to perform a live search of employees stored in the database. app.get('/delete' , isLoggedIn , (req , res) ...

Bot on Discord using Discord.Js that generates unique invites for users

I'm trying to find a way to generate an invite link for users to keep track of invites. The code I have currently is creating the invite for the Bot instead. const channel = client.channels.cache.find(channel => channel.id === config.server.channel ...

Updating the handler function for AutoComplete with Checkbox in Material UI using React JS

I am looking to include an <AutoComplete /> field in my form. The options for this field are fetched through a get request, and here is the result displayed in the console. [ { "uid": "c34bb0ed-9f63-4803-8639-a42c7e2a8fb0&q ...

Can a synchronous loop be executed using Promises in any way?

I have a basic loop with a function that returns a Promise. Here's what it looks like: for (let i = 0; i < categories.length; i++) { parseCategory(categories[i]).then(function() { // now move on to the next category }) } Is there ...

Angular7 & Electron: Resolving the Issue of Loading Local Resources

I am encountering difficulties while working with electron. Although I can successfully load my project using ng serve, I encounter an error when attempting to open it with electron as shown in the developer tools Not allowed to load local resource: fil ...

Finding the correct column in a drop-down menu based on a table array using AngularJS

In my controller, I have data like this: $scope.operationData = [ { "label" : "Inventory", "labelType" : "Master Tables", "type" : "PROCESSOR", "outputStreams" : 1, "elementType" : "TABLE", "name" : ...

Retrieving precise information from the backend database by simply clicking a button

As a new full stack programmer, I find myself in a challenging situation. The root of my problem lies in the backend table where data is stored and retrieved in JSON format as an array of objects. My task is to display specific data on my HTML page when a ...

Why does the Model appear to be Null when using an Ajax Call in MVC?

Exploring MVC for the first time and trying to figure out how to pass the Model into an Ajax call. The code below is what I've come up with, but it keeps passing NULL to all properties. $("#btnsubmit").click(function () { alert('hell ...