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