JavaScript's Ajax functionality might only send the final piece of data in an array

My current challenge involves sending multiple data packets from my application using JSON Ajax in JavaScript. Despite having more than one packet of data, the issue I'm facing is that when I send the data through Ajax, it only sends the last data packet.

To give an example, if I were to send two data packets, Ajax would indeed send two data packets, but they both end up containing the same information (which is from the last data packet).

Below is a snippet of my code:


for(var i=0;i<data.length;) {
    /*var d = new Date();
    d.setTime(data[i].updated);*/
    var send2 = {};
    send2.nama= data[i].name;
    send2.rumahsakit = data[i].hospital;

    //step 1
    alert("step 1"+send2.nama);

    var client = "coba";
    var Idku = data[i].unik;

    //clientID
    var request2 = {};
    request2.jsonrpc = "2.0";
    request2.id = "load_reg"+Idku+"";
    request2.method = "registrasi:loadByClientUnik";
    request2.params = [client,Idku];
    var postData = JSON.stringify(request2);
    var postArray  = {json:postData};   

    $.ajax({
        type: 'POST',
        url: 'service.php',
        data: postArray,
        dataType:'json',
        success: function(result){      
            alert(send2.nama);

            if(result.result == -1){
                var requestx = {};
                requestx.jsonrpc = "2.0";
                requestx.id = "store_reg";
                requestx.method = "registrasi:store";
                requestx.params = [send];

                // More AJAX calls follow here...
            } else {
                // Updated AJAX code with context included...
            }
        },
        error: function(e){
            console.log(e);
            alert(e);
        }

    }); 

    i++;
}
getData();
}

Example behavior: When sending 2 data packets where the first has name = 1 and the second has name = 2, the output should be as follows:

output :

  • alert step 1 prints 1

  • alert step 1 prints 2

  • alert step 2 prints 2

  • alert step 2 prints 2

The desired output is:

  • alert step 1 prints 1

  • alert step 2 prints 1

  • alert step 1 prints 2

  • alert step 2 prints 2

This version includes updated code with the addition of context...is this correct??

Updated :

I have resolved this issue by referring to this helpful link: jQuery ajax inside a loop problem

Answer №1

element, it appears that your code is currently sending both requests sequentially in order, which aligns with your intended behavior. The initial debug output occurs due to the asynchronous nature of $.ajax() calls. These calls send a request and then proceed with executing the code without waiting for a response from the server. Consequently, your outer loop finishes its execution (twice in this case) before any responses are received, and the success callbacks are triggered afterward. Once both responses are received, the success callbacks execute accordingly. However, by that point, the local variable send2.nama holds the value "2," resulting in the repeated output of "step 2 print 2" instead of the expected sequence. It's essential to address this potential source of errors when making requests within these callbacks since they rely on local variables. Utilizing the context parameter can help mitigate this issue: $.ajax({ // ... context: { send2: send2 }, success: function (result) { // "this" refers to the context object alert(this.send2.nama); // ... } }); If your goal is indeed to wait for the first response before sending the second request, some restructuring of the code may be necessary. Invoking a function within the first request's success callback to trigger the second request could achieve this desired sequential behavior.

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 collect and store data from various sources in an HTML interface to a Google Spreadsheet?

Currently, I have a spreadsheet with a button that is supposed to link to a function in my Google Apps Script called openInputDialog. The goal is for this button to open an HTML UI where users can input text into five fields. This input should then be adde ...

Exploring a JSON API with VB.net

Hello everyone, I need help searching for a specific value in a JSON string. Below is the code I am currently using: Dim ser As JObject = JObject.Parse(reader.ReadToEnd()) Dim data As List(Of JToken) = ser.Children().ToList Response.Write(se ...

Utilizing Datatables with mysqli for server-side processing through JSON

I'm encountering an issue with my implementation of datatables. Certain pages are crashing due to the large amount of data being fetched from the database. I attempted to resolve this by utilizing server-side processing. Despite following the examples ...

Split the data into two distinct lists based on a specific condition in Flutter

[ { "name": "ITEM-1", "desc": "DESCRIPTION", "listNo" :"0" }, { "name": "ITEM-2", "desc": "DESCRIPTION", &q ...

Receive real-time server updates via AJAX

My current setup involves an ajax app that checks the server for updates every 10 seconds using setInterval(...). However, I am concerned about the resource intensity of this method. Is there a more efficient way to receive real-time updates from the serve ...

Exploring the intricacies of Django and JQuery interdependent dropdowns: mastering the art of Ajax

I recently followed a tutorial on creating interdependent dropdowns using Django, JQuery, and Ajax. Here is the link to the tutorial: In my project, I have an inline-formset where selecting a product type should only display products within that type. Up ...

Creating a Prismoid Shape Using Three.js

Currently, I am utilizing Three.js and my objective is to construct a pyramid shape with its apex removed. The base of the pyramid should be a rectangle instead of a square, while the top should also be a rectangle, but not in equal proportions. Here is a ...

The JSON data received from a jQuery Ajax call is not properly formatted when processed in PHP

When sending JSON data to a PHP script via a JQuery AJAX request, I encountered an issue where the data was behaving like a string instead of an associative array. JavaScript var all_data = []; $.each($("[id*=card]"), function(i, value) { var name_a = ...

React function component often uses the "this" keyword in order to

When looking at the code below, I encountered an error stating that handleClick is not defined. I attempted to use onClick={this.handleClick} but it did not resolve the issue. How can I properly access the handleClick function for the onClick event of th ...

Using Node.js and Express with MySQL to store documents (outcomes)

I recently developed an Express App using Node.js Express v4.16.2 MySQL v2.15.0 In my app, I have configured MySQL as a Document Store Columns id: integer value: JSON When querying the MySQL Database with mysql, I receive the following result: Ro ...

Tips for transferring form data to a popup form by clicking a link in MVC

I'm currently working on an MVC project where I have successfully created a table. Everything is functioning properly, but now I need to implement a feature where clicking on a link in a specific row opens a popup form displaying the data from that ro ...

Focus on a primary window

When a new window is opened using the target attribute of _blank, is it possible to target links to open in the original "parent" window? Appreciate your help! ...

Issues with AJAX file uploading functionality are preventing users from successfully uploading files

I need help with uploading text files via AJAX on a browser. I have tried implementing the code, but it seems like the file is not being uploaded successfully as var_dump($files) displays array(0). HTML: <form id="uploadsql" action="upload.js" method= ...

Issues with rendering AngularJS onto an HTML page are currently being experienced

I was attempting to learn AngularJs in order to improve my front-end development skills, but unfortunately I ran into some issues. Despite following the video tutorials on their site step by step, I couldn't get it to render correctly. Here's the ...

What is the best way to prepopulate form values in a Vue object?

Sharing my code snippet: HTML: <div id="user-panel"> <div class="text-center"> {{ fillItem }} </div> <form method="POST" action="http://site5/user_account/experiences/17" accept-charset="UTF-8" v-on:s ...

Fixing the 'Unexpected identifier' error when utilizing an imported function from a separate file

I've been attempting to utilize a function that I previously defined in another file and exported. However, when I try to use it and run the node server, an error is thrown as displayed below. Could this be due to a syntax error on my part? The path ...

The OpenWeatherMap API is displaying 'undefined' as a response

I've been encountering some issues with my weather app project due to lack of clarity in my previous questions. To be more specific, every time I attempt to retrieve weather information in JSON format using the fetch method, it keeps returning undefin ...

Mastering browser console manipulation using a script

I need help finding a way to automate a task on a website, such as clicking a button. I have a JavaScript code that can perform the task when run from the browser console. However, I want to find a way to pass this JavaScript code to the console without ...

A guide on how to mention users in Discord.js

I attempted to get the bot to mention a member using @, but when I used message.channel.send(<@id>+"text") it showed an error message saying unexpected sign '<'. Is there a way to successfully mention members with the bot? ...

Exploring the interplay of dynamic images and Ajax functionality within the ASP.NET

Currently, I am facing an issue with displaying a detail partial view using ajax and colorbox. The functionality works perfectly the first time it is clicked, but on subsequent attempts, the GetGraph function does not run, causing the initial image to disp ...