Utilize Nested jQuery Ajax to transfer the data from the global variable received in the first ajax response to the second ajax request for further processing

I am aware of the asynchronous issues with JavaScript, which is why I have created two functions to encapsulate AJAX calls in reusable functions. These functions work perfectly fine when used with callbacks.

However, I am facing an issue where I need a variable from the getBlocks() AJAX call to be passed to the second AJAX call getAcct(). In the first AJAX call, I have a for loop that triggers the second AJAX call on each iteration to retrieve the account name. I have tried setting a global variable qq, but it always shows as undefined.

How can I resolve this issue?

// Function to get blockchain transactions
function getBlocks(acct, ip, pikachu) {
     $.ajax({
         url: 'http://'+ ip +'/nxt?=%2Fnxt&requestType=getBlockchainTransactions&account=' + acct + '+&withMessage=true',
         dataType: 'json',
         success: pikachu
     }); // Get account name
}

// Function to get account info
function getAcct(acct, ip, zelda) {
     $.ajax({
         url: 'http://'+ ip +'/nxt?=%2Fnxt&requestType=getAccount&account=' +  acct  + '+&withMessage=true',
         dataType: 'json',
         success: zelda
     }); // Get account name
}


getBlocks(nxtacct, nxtip, function(response) {
      var xx = [];
      xx = response.transactions;

      for( i = 0; i < xx.length; i++)  {
        yy = xx[i].senderRS;
        var qq;

        getAcct(yy, nxtip, function(response) {
          qq = response.name;
        });

        jQuery(targetb).append("<tr>");
        jQuery(targetb).append("<td>" + xx[i].amountNQT +"</td>");
        jQuery(targetb).append("<td>" + xx[i].feeNQT + "</td>");
        jQuery(targetb).append('<td><a href="https://test.nxtportal.org/accounts/'+ xx[i].sender +'" target="_blank">' + qq + "<em>" + yy + "</em>"  + "</a></td>");
        jQuery(targetb).append("<td>" + xx[i].recipientRS + "</td>");
        jQuery(targetb).append("<td>" + xx[i].message+ "</td>");
        jQuery(targetb).append("<td>" + date +"</td>");
        jQuery(targetb).append("</tr>");
     } //for
});

Answer №1

To access and define custom AJAX properties, you can utilize the this keyword. When making an AJAX call, simply specify the desired property within the call itself.

// Retrieve next account information
function getAccount(accountName, ipAddress, customValue, callback) {
    $.ajax({
         url: '...',
         dataType: 'json',
         myCustomProperty: customValue,
         success: callback
     }); 
}

You can then access the custom property inside the callback function, referenced as this.myCustomProperty.

function callbackFunction(response) {
    var customPropertyValue = this.myCustomProperty;

    // Perform actions with the value
}

For more details, you can visit this link.

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

Leveraging replaceWith() alongside animate or scroll methods can enhance the user

Can we switch one div with another div while incorporating an animation effect, such that the old div slides to the left while the new one slides in from the right side of the page? My goal is to have both divs present on the page simultaneously while the ...

Using jQuery to transform a JSON array within a JSON object into an array

I am attempting to convert the JSON data below: { "questions": [ { "question#1": "How much is 3+1", "correct answer": 1, "answers": { "ans#1": "5", "ans#2": "4", ...

Having trouble displaying the image on the screen with Material UI and React while using Higher Order Components (HOC) for

I'm facing an issue with displaying an image on my Material UI Card. Despite checking the directory and ensuring it's correct, the image still doesn't show up. Additionally, I need assistance in modularizing my code to avoid repetition. I at ...

two clicks on the sc-player

I've encountered a problem of duplicated events when using sc-player.js. I'm trying to change an iframe when a li element is clicked, but the play/pause buttons also trigger the same li click event. Is there a way to control the play/pause funct ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

Generate items above the mesh

I'm currently working on a procedural terrain generation project. I have successfully generated terrain using Perlin noise, and now I want to add procedural grass generation with some specific constraints. My goal is to only generate grass within a c ...

The script titled "begin" is nowhere to be found within the nest

After setting up NestJS, I attempted to run it in VSCode as instructed in the documentation. The command that I used was: npm run start However, I encountered an error stating that the script "start" was missing. According to the documentation, running th ...

I'm having trouble adding a background image, even though I have set it to static. What could be

I attempted to add a background image to my Django website, but unfortunately, it was not successful. I followed the steps provided in this Stack Overflow answer here, however, it did not work. I even made changes to the database by migrating them, but s ...

Experience a captivating Angular slideshow carousel that resets when you click on a dot button, all powered by the magical capabilities of

Check out this Stackblitz Link for a working sample. I have developed an angular carousel slider component using rxjs. Each slide changes after 5 seconds and everything is working smoothly. However, I am facing an issue where clicking on a particular dot ...

Invalid element type detected. A string was expected, but instead found undefined

Following a recent update of next-auth, an unexpected error has surfaced: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your compon ...

Choosing a value in VueORSelecting

Having some issues with vue select. I have a function that should return the id as the value and display the text as an option, but it is currently returning the full object of the selected value. For instance: I am fetching selectable options from my bac ...

Looking to decrease Cumulative Layout Shift (CLS) on the NextJS website for enhanced performance

I have chosen to use NextJS with Mantine for my website development. Utilizing createStyles, I have added custom stylings and incorporated various mantine components into the design. After deploying the site on Vercel, I discovered that all performance me ...

How can we effectively implement an auto login feature using JWT?

Having recently delved into jwt authorization, I find myself transitioning from traditional user and password authorization to a more secure method. After grasping the fundamentals of jwt, I am eager to implement it in my workflow and have a question: Upo ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Executing a function that includes showModalDialog outside of an iframe might display the incorrect page

This website structure looks like: `--main.html `--dialog.html `--folder `--iframe.html The code for each page is as follows: main.html: <html> <head> <script type="text/javascript"> function t ...

Modify the indentation format in CSS/JS

When the Tab key is pressed in an HTML page and the tabbed link gets highlighted, is it feasible to customize the style of that highlight? ...

Utilizing Typescript generics in scenarios with arguments that may be either a value or a callback function

Here's the issue: I need to pass T, which could be a string, number, boolean, object, array, or a function. The problem is I can't figure out how to handle ab("hello") in this scenario and return T as a value. function a<T>(ab: T | ((v: T) ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

When the onclick event is triggered, the return value will execute after the onclient

After my onclientclick event finishes, I am trying to run my onclick event. However, regardless of whether my checkbox is selected or not, the program keeps prompting me to "Please select at least one to delete." Can anyone help me figure out why this is h ...