Modifying worldwide variables within an ajax request

After spending considerable time attempting to achieve the desired outcome, I am faced with a challenge. My goal is to append the object from the initial ajax call after the second ajax call. However, it appears that the for loop is altering the value to the last result before appending the information, resulting in the last post being appended each time.

    var scribjson = 
{
    "user_id" : localStorage.viewing,
};
scribjs = JSON.stringify(scribjson);
var scrib = {json:scribjs};
$.ajax({
    type: "POST",
    url: "getScribbles.php",
    data: scrib,
    success: function(result)
    {     
        var obj = jQuery.parseJSON(result);
        for(var i = 0; i < obj.length; i+=1)
        {   
            var userjson = 
            {
                "user_id" : obj[i].user_id
            };
            userjs = JSON.stringify(userjson);
            var user = {json:userjs};
            localStorage.post = obj[i].post;
            $.ajax({
                type: "POST",
                url: "getRequestsInfo.php",
                data: user,
                success: function(result)
                {     
                    var obj2 = jQuery.parseJSON(result);
                    $('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
                    $('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
                },
                error: function()
                {
                    alert('An Error has occured, please try again.');
                }
            });

        }
    },
    error: function()
    {
        alert('An Error has occured, please try again.');
    }
});

Answer №1

When making ajax calls, it appears that all the success functions of the inner ajax call are executed after the loop has completed. As a result, the variable i will always hold the last iterated value.

To address this issue, you can try the following approach:

(function(i)
{

    $.ajax({
        type: "POST",
        url: "getRequestsInfo.php",
        data: user,
        success: function(result)
        {     
            var obj2 = jQuery.parseJSON(result);
            $('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
            $('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
        },
        error: function()
        {
            alert('An Error has occured, please try again.');
        }
    });
})(i);

By enclosing the ajax call within a closure on i, each call will have its own copy of the current value, preventing any conflicts.

Answer №2

Implement an IIFE in your code:

success: (function(i){return function(result) {
    var obj2 = jQuery.parseJSON(result);
    $('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
    $('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
}})(i),

In the current implementation, your loop-generated ajax success handlers have a direct reference to the counter itself, which may cause issues as it reaches its final value.

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

Tips on combining JSON array elements into a new JSON array using NodeJS

Is it possible to manipulate a JSON array with 100 objects? Each object contains key values for Job Number, Tax Amount, Line Total, and Line Total plus Tax. The task is to create a new JSON array with Job Number, Total Tax Amount, Sum of Tax Items, and Sum ...

Building a table using a JSON object in a React component

I have been dynamically creating a table in React based on the API response received. data = {"name":"tom", "age":23, "group":null, "phone":xxx} Everything was working fine until I encountered a scenario w ...

Having trouble pinpointing the source of the error and finding a solution

*While attempting to parse some data through JSON, I encountered an issue where clicking on a specific button caused the parsing activity to stop working. The rest of the app is functioning properly except for this particular button.* Main Activity Button ...

Apply a specific CSS class to a division depending on the currently active cookie

I have implemented cookies on specific pages using https://github.com/carhartl/jquery-cookie. Could someone guide me on how to apply a CSS class to an ID (e.g., adding class .red to #mouse if the cookie named "socks" is active)? For example: If there is ...

Vue JS: Easily Calculate the Total Sum of All Columns

An example of a query in the backend controller public function show($id) { $structural = DB::table('attendance')->where('payroll_daily_id',$id) ->where('assignment','STRUCTURAL') -&g ...

"Utilizing Rails with the power of Ajax and Jquery to enhance the Post

Currently, I am facing an issue with an AJAX post data call in my Rails project. The data is successfully entering the database, however, the SUCCESS function is not functioning as expected. When trying to execute an alert within the success function, it d ...

The content section sits discreetly behind the sidebar

Upon loading my Bootstrap 5 webpage, the toggle button successfully moves the navbar and body section to show or hide the full sidebar. However, an issue arises where the body section goes behind the sidebar when using the toggle button. Below is a portio ...

Setting up Fancytree to Fetch Data via AJAX

I've been attempting to make it work for hours without success. I am currently trying to set up Fancytree with ajax. Here is my current progress: $(function(){ $("#tree").fancytree({ initAjax: {url: "/ajaxData.do", d ...

Using the spread operator in React to distribute JSX elements within a map function

I am struggling with mapping over an array within another array to create a Picker and am having difficulty returning JSX elements instead of an array of JSX elements. Here is the code example: {modelA.map((mA) => { const pickerItems = mA.modelB.m ...

encasing a snippet of code within a customized hyperlink

Here's the following "embed code" for an Instagram photo featuring Kim Kardashian. I'm curious - how can one encapsulate this embed code within an <a> tag (or another tag) so that clicking on the image will redirect to www.google.com? < ...

What is the best way to incorporate user-provided values into a dynamic URL?

I am trying to create a feature where users can input a value and then click a button that will take them to a URL tailored to their entry. Here is my current code, but I am facing an issue - the user_input data does not seem to be passed to the URL when ...

The optimal method for computing the Fibonacci sequence using JavaScript

Improving my skills in optimizing algorithms and understanding big-o notation is a priority for me. I devised the following function to compute the n-th Fibonacci number. It works well for higher inputs, but I wonder how I can enhance it. What are the dow ...

Integrating PHP code into a React.js application can provide

I am currently integrating react.js into a section of my app and exploring the possibility of embedding some PHP code into react.js. This would allow me to avoid having to completely rewrite the backend that was originally written in PHP. Here's an ex ...

Tips for safeguarding against brute force attacks when submitting ajax forms

Let's say I have a file called login.php. In this case, login.php accepts GET or POST parameters for username and password and returns true if the login is successful and false if it fails. This allows other pages to access it through AJAX. My conce ...

Understanding the basics of Maven imports: troubleshooting class not found errors

After adding the following to my pom.xml: <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20170516</version> </dependency> The desired json classes, such as JSONArray, ...

Encountering an issue with undefined ID when utilizing a radio input field in Vue JS

I'm facing an issue and I hope you can assist me with it. My webpage contains Vue scripts and a list of radio selections rendered via Liquid tag and GraphQL results. The problem arises when I click the submit button or select a radio option, resultin ...

What is the process for extracting the differences between two or three files and merging them together in Node.js?

Recently, I've been experimenting with webpack and successfully managed to output and transform es5 build to include nomodule in the tags directly from HtmlWebpackPlugin using hooks. Similarly, for the es6 build, I added type="module". Howe ...

`Cannot Get jQuery ScrollTop Function to Work for 2nd Element`

Having trouble with an issue. Let me explain. I implemented a scrollTop Jquery on page load that scrolls down after a delay to prompt user action. However, I'm facing a problem where another scrollTop doesn't work after clicking buttons "#b3,#b3 ...

Oops! There was an issue with the form field - make sure to include a MatFormFieldControl for proper validation on the

I am working on an Angular application that utilizes Angular Material components. Despite conducting extensive research online, I have not been able to find a suitable solution to the specific error message I have encountered. The issue revolves around a ...

Automatically redirect to the linked page once the video concludes

Would it be feasible for a html5 video to trigger the opening of a new page upon completion? What would be the approach to achieve this using javascript? ...