0

I want to send data from my application with json ajax in JavaScript. I have more than one packet of data, but when I send my data through ajax it only sends the last data packet.

For example, I send two data packets, then ajax sends two data packets but they both contain the same data(the last data packet).

Here is 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];
//request2.params = akun.value;

var postData = JSON.stringify(request2);

var postArray  = {json:postData};   


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

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

    var postDatax = JSON.stringify(requestx);

    var postArrayx  = {json:postDatax};

    $.ajax({
    type: 'POST',
    url: '/service.php',
    data: postArrayx,
    dataType:'json',
    //async: false,
    success: function(result){
    //alert("sukses");
    },
    error: function(e){
    console.log(e);
    alert(e);
    }       });

    }else{
    alert(send2.nama);
    var request = {};
    request.jsonrpc = "2.0";
    request.id = "store_reg";
    request.method = "registrasi:storeById";
    request.params = [result.result,send2];

    var postData2 = JSON.stringify(request);

    var postArray2  = {json:postData2};

    $.ajax({
    type: 'POST',
    url: '/service.php',
    data: postArray2,
    dataType:'json',
    //async: false,
    success: function(result){
    //send2 = "";
    //alert("sukses ID");
    },
    error: function(e){
    console.log(e);
    alert(e);
    }
    });

    }
    },
    error: function(e){
        console.log(e);
        alert(e);
    }

}); 
//return false;
i++;
}
getData();
}

Example behavior: I send 2 data packets, 1st has name = 1 and the 2nd has name = 2, then I send both packets:

output :

  • alert step 1 print 1

  • alert step 1 print 2

  • alert step 2 print 2

  • alert step 2 print 2

I want this output :

  • alert step 1 print 1

  • alert step 2 print 1

  • alert step 1 print 2

  • alert step 2 print 2

        }else{
    alert(send2.nama);
    var request = {};
    request.jsonrpc = "2.0";
    request.id = "store_reg";
    request.method = "registrasi:storeById";
    request.params = [result.result,send2];
    
    var postData2 = JSON.stringify(request);
    
    var postArray2  = {json:postData2};
    
    $.ajax({
    type: 'POST',
    url: 'http://10.126.14.116/portable_med_services/service.php',
    data: postArray2,
    dataType:'json',
    //context set
    context: { send2: send2 },
    //async: false,
    success: function(result){
    //send2 = "";
    //alert("sukses ID");
    },
    error: function(e){
    console.log(e);
    alert(e);
    }
    });
    

This is my updated code with adding context...am I right??

update :

I already fixed this issue following this issue... jQuery ajax inside a loop problem

Community
  • 1
  • 1
  • 1
    possible duplicate of [jQuery ajax inside a loop problem](http://stackoverflow.com/questions/2687679/jquery-ajax-inside-a-loop-problem) – Felix Kling Jul 23 '13 at 10:24

1 Answers1

0

Your code actually sends both requests one after another (step 1), in order, like you probably want it to.

You get the first debug output due to the asynchronous nature of $.ajax() calls. They send the request and continue with the code execution-- they don't block and they don't wait for the response from the server. That's why your outer/main for loop executes all the way to the end (2 times in your case) before any response is received and the code inside the success callbacks is executed.

When the 2 responses are received, the success callbacks are executed (2 times, once for each response), however at that point in time your local variable send2.nama has the value of "2". That's why you get the output "step 2 print 2" twice, instead of "step 2 print 1" and "step 2 print 2".

This will likely also be the error cause for other requests that you make from inside the success callbacks, since you are using local variables inside the callbacks. You should be using the context parameter instead:

$.ajax({
  // ...
  context: { send2: send2 },
  success: function (result) {
    // "this" has the value of the context object
    alert(this.send2.nama);
    // ...
  }
});

I am not sure if your intention is really to send the 2nd request only after the 1st response is already received, but if it is, then you will have to refactor the code a bit and send the 2nd request from a function invoked from inside the success callback of the 1st request.

Ma3x
  • 5,761
  • 2
  • 17
  • 22
  • can i stop "for" for a while..? and then send 1st data.. and then do for again then send 2nd data..?? or any option to replace AJAX in javacript ?? *thanks for your answer @Ma3x – Ah Wirayudha Jul 12 '13 at 18:12
  • I guess you want to send the AJAX synchronously. There is an option to do that with async: false, but there are some problems related to that, e.g. browser window freezing until the response is received. The docs also state that it's deprecated since 1.8 under some conditions (http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings). – Ma3x Jul 12 '13 at 18:17
  • thanks.. i will try it when i go to lab tomorrow morning.. :) – Ah Wirayudha Jul 12 '13 at 18:18
  • i try it and failed, but i don't know my code is right or not.. can you check my code?? i edit my post.. – Ah Wirayudha Jul 15 '13 at 06:54
  • @AhWirayudha: Yes, I see you added context: { send2: send2 }, that's fine. Then inside the success callback you need to use `this` instead of `send2` (so instead of `send2.nama` use `this.nama`). – Ma3x Jul 15 '13 at 14:18
  • i fix this issue with this issue http://stackoverflow.com/questions/2687679/jquery-ajax-inside-a-loop-problem – Ah Wirayudha Jul 22 '13 at 17:51