The Ajax request (b) fired off during the callback of an earlier Ajax request (a) finishes before (a) itself is fully

I encountered an issue with my code where an ajax call, referred to as callback (b), was expected to depend on the success of another ajax call, known as callback (a). Surprisingly, callback (b) completed successfully before its parent ajax call (a) finished.

Here is the Javascript code:

var ajaxAdata; //global

ajaxA(ajaxB(1));

function ajaxA(callback){
       FB.api('/me', function(response) { //ajax call(a)
            ajaxAdata = response.id; 
            callback(); // this completes before ajax call(a) completes
       }
}

ajaxB = function(isPublic) {
       .getJSON(){ //ajax call (b)
            console.log(ajaxAdata); // necessary ajaxAdata returns undefined
        }
}

Is there a misunderstanding on my part when it comes to JavaScript? I have learned that using a callback function is the correct approach for handling asynchronous calls. However, does JavaScript preemptively execute the ajaxB function and initiate .getJSON() even before the FB.api() call has concluded?

Answer №1

Your decision

ajaxX(ajaxY(1));

triggers ajaxY(1) prior to the invocation of ajaxX in order to provide the parameter value for ajaxX.

The correct approach would be

ajaxX(ajaxY, 1);

and

function ajaxX(callback, param){
       FB.api('/me', function(response) { //ajax call(a)
            ajaxAdata = response.id; 
            callback(param); // this is executed before ajax call(a) is finished
       }
}

Answer №2

The correct order is:

ajaxA(function() {ajaxB(1);} );

Prior to this, you were executing the ajaxB() function first and passing its return value (undefined) as the callback parameter to ajaxA(). The desired approach is to pass a function that contains the call to ajaxB() as the callback instead.

Answer №3

ajaxA(ajaxB(1));

Executing ajaxB first, then using the result as an argument for ajaxA.

Remember to pass in the function itself, not the result.

Try this:

ajaxA(ajaxB);

In ajaxA, pass your argument to the callback like this:

callback(1);

Answer №4

Executing ajaxB is crucial at this point:

ajaxB(1)

In my opinion, one possible solution is to return a function from ajaxB, or alternatively, figure out a way to pass the isPublic flag to your ajaxA function like so:

ajaxA(ajaxB, 1);

function ajaxA(callback, isPublic){
      FB.api('/me', function(response) { //ajax call(a)
            ajaxAdata = response.id; 
            callback(isPublic); //this action is completed before ajax call(a) finishes
       }
}

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

MUI: Autocomplete received an invalid value. None of the options correspond to the value of `0`

Currently, I am utilizing the MUI autocomplete feature in conjunction with react-hook-form. I have meticulously followed the guidance provided in this insightful response. ControlledAutoComplete.jsx import { Autocomplete, TextField } from "@mui/mater ...

Display and conceal elements within predetermined time intervals using jQuery, while ensuring that the final element remains visible

Is there a way to automatically hide div1 and show div2 after a set amount of time, let's say 10 seconds or 15 seconds? I came across this thread: Show and hide divs at a specific time interval using jQuery, However, the solution provided in the po ...

Changes to the className of a React component will trigger a re-render of

When the className of the parent changes, React children will re-render. import React from 'react'; import { useSelector } from 'react-redux'; import items from './ItemsList.js'; import Item from './Item'; import &ap ...

Stopping the Game Loop in Windows Phone 8.1 with WinJS

Despite everything working smoothly, I am facing an issue with stopping the game loop when the Start button is pressed and the app is moved to the background. The event handler for suspend, app.oncheckpoint = function(args) {}, does not seem to fire for t ...

An Illustration of Basic Nested Controller within Directive Parameters

Check out this code snippet app.directive('hello', function() { return { restrict: "E", templateUrl: "/Angular/Modules/Selector.html", controller: function () { this.message = [enter the attribute message he ...

Do not include objects in the search results that lack necessary information

My ng-repeat code looks like this: <div layout="row" flex layout-wrap layout-margin layout-padding> <tile ng-repeat="camp in ctrl.camps | filter:{ctrl.search} track by $index"></tile> </div> The ctrl.camps object array is str ...

The conversion of AJAX crawling into hashbang URLs

Currently, I am working on a website that is AJAX-crawlable using Google's AJAX crawling guidelines. However, there are some aspects of this process that are unclear to me. In the backend of my application, I filter out the _escaped_fragment_ paramete ...

Tips for extracting information from a website that uses Javascript with Python?

I am currently working on a web scraping project to extract data from the DoorDash website specifically for restaurants located in Chicago. The goal is to gather information about all the restaurant listings in the city, such as reviews, ratings, cuisine, ...

guarantee that a DOM setting is ready for enzyme

Encountering an issue with Enzyme's mount function while testing a React application in Jest from the command line. The error message indicates that a DOM environment is not loaded, leading to speculation about the need to set up JSDOM. However, it&ap ...

Using AngularJS controller to implement filtering functionality

I am a beginner at using Angular and have successfully implemented a filter to translate text for localization in my HTML view: <input type="button" class="btn btn-link" value="{{'weeklyOrdersPage.reposting' | translate}}" ng-click="sortBy(&a ...

I encountered an error while setting up Vue.js on my computer

While attempting to install Vue.js on my system using the command npm i -g @vue/cli, I encountered the following error: npm WARN cleanup Failed to remove some directories [ npm WARN cleanup [ npm WARN cleanup 'C:\\Users\\ ...

Triggering JavaScript Function When Scrolling in Overflowed DIV

After using jQuery and searching for various ways to make this script work, I finally found a solution that works for my index.html file. <div style="overflow-y:scroll; height:300px"> <div style="background-color:black; height:500px"> </div ...

Guide to extracting a specific value from a JSON object with JavaScript

When working with JavaScript and fetching data from an API, the structure of the data retrieved may look something like this: [{ "word":"gentleman", "score":42722, "tags":["syn","n"] }, { "word":"serviceman", "score":38277, "tags":[ ...

What is the reason behind this HTML/CSS/jQuery code functioning exclusively in CodePen?

I have encountered an issue where this code functions properly in JSFiddle, but not when run locally in Chrome or Firefox. I suspect there may be an error in how the CSS or JavaScript files are being linked. In the Firefox console, I am receiving an error ...

Unable to transmit Props to Component - Fluctuating Behavior

I developed a React.js and Next.js application where I needed to pass the User object to all pages. My plan was to then pass this User component to the Head component in order to display different navigation options based on the user's role. Here is w ...

Connecting a Node.js Redis client to a Redis cloud server: Step-by-step guide

const redis = require('redis'); const client = redis.createClient({ host: 'redis-19606.redislabs.com', port: 19606, password: 'password' }); client.on('ready', () => { console.log('redis is connecte ...

Maintaining the current image while awaiting the completion of the new image update

I have successfully implemented a script using setInterval along with the jQuery load function to periodically update an image tag. var refresh_days = setInterval(function() { $('#box_name').load("dynamic.php");}, 1000 ); While this setup wo ...

Page_Load method does not get invoked during a POST request

After creating a web page with jquery ajax calls, I realized that the Page_Load method is not triggered for a jquery ajax POST request. However, I require the Page_Load call to access the name of the logged-in user and store it in the database along with t ...

Enhancing Navbar Design with Tailwind CSS in NextJS and React

I have not worked with React in a while and just started learning Next.Js. I am trying to figure out how to change the background of my Navbar using Tailwind CSS based on a boolean value "current" (true/false) depending on which page the user is on with Ne ...

Navigating to and Revealing a Division by Clicking

Check out this code snippet: <a onclick="$('a[href=\'#tab-customtab\']').trigger('click');">Enquire Now</a> <div id="tab-customtab"></div> This piece of code triggers the opening of the #ta ...