1

I have a question to the behaviour of this AJAX call shown below which I dont understand.

var checkBoxes = document.getElementsByName("newInclCheckBox");
for(var i = 0; i<checkBoxes.length; i++
{
  if(checkBoxes[i].checked)
  {
    var name2 = getTabKeyFromDescription(checkBoxes[i].value);
    var tablenr2 = checkBoxes[i].getAttribute("data-tablenr");
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function()
    {
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
      {

        document.getElementById('newIncl_LogBox').innerHTML += xmlhttp.responseText;

      }
    }
    xmlhttp.open("GET", "../PHPScripts/getInclusions.php?q=add&name1=" + name1 + "&tablenr1=" + tablenr1 + "&name2=" + name2 + "&tablenr2=" + tablenr2, true);
    xmlhttp.send();
  }
}

As you can see, the AJAX Call is inside a for-loop and gets called several times while looping through checkBoxes.

The PHP-Skript getInclusions.php completes each request successfully, but somehow only the last xmlhttp.responseText gets written in my LogBox.

I would understand this behaviour if i had written

document.getElementById('newIncl_LogBox').innerHTML = xmlhttp.responseText;

(without += Operator).

Why is the writing in the logbox not as expected? Any help is greatly appreciated!

Jbartmann
  • 1,459
  • 4
  • 24
  • 42
  • possible duplicate of [Asynchronous Process inside a javascript for loop](http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop), or see http://stackoverflow.com/questions/4288759/asynchronous-for-cycle-in-javascript or http://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript or search for "asynchronous for loop javascript". – Matt Nov 25 '13 at 16:15
  • 1
    Make sure you are getting HTML content from server for each ajax call. And i see syntax issue in for loop. for(var i = 0; i – Murali Mopuru Nov 25 '13 at 16:38
  • 1
    the missing parenthesis seems to be a typing error. In my code i have it right :) – Jbartmann Nov 26 '13 at 08:00

1 Answers1

1

You can call ajax synchronously in for loop then it will execute one by one like that and use this code in your code as usual.

This is syncronous ajax call example.

urllink="../PHPScripts/getInclusions.php?q=add&name1=" + name1 + "&tablenr1=" + tablenr1 + "&name2=" + name2 + "&tablenr2=" + tablenr2;

$.ajax({
    async: "false",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: urllink,
        success: function(jsonData) {
            alert("jsonData =" + jsonData);
            return jsonData;
        }
    });  
Ashish Jain
  • 760
  • 1
  • 8
  • 23
  • 1
    Thanks! Even though I don't use JQuery, setting asynchronous to false did the job. For anyone who faces the same issues: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp – Jbartmann Nov 26 '13 at 07:58