views:

24

answers:

1

Hello.

I have a problem in the following code:

//quesry the db for image information
function queryDB (parameters) {
     var parameters = "p="+parameters;
     alert ("hello");


if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        // use the info
  alert (xmlhttp.responseText);
    }
  } 

    xmlhttp.open("POST", "js/imagelist.php", true);
    //Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}

which is call from this function:

function buildGallery() {

    var images = document.getElementsByTagName("img");
    for (var i = 0; i< images.length; i++) {
        if (images[i].getAttribute("id").split("_")[0] == "onshow") {

            var parameters = images[i].getAttribute("id").split("_")[1];

            queryDB (parameters);
        }
    }

}

When I remove the alert statement 4 lines down in the queryDB function I hit problems. This function is being called by a loop, and without the alert, I only get results for the last value sent to this function. With it, I get everything I was expecting and really I'm at a loss to know why.

I've heard that this may be a timing issue as I'm sending new requests before the old one is finished. I also heard polling being mentioned, but I can't find any information detailed enough.

I'm new to synchronous services and I'm not really aware of the issues.

+1  A: 

Actually, the problem is that you're using a global variable. Add:

var xmlhttp;

to the beginning of queryDB

As TriLLi notes, the alert hides this problem by giving the prior call time to finish before overwriting it.

Matthew Flaschen
sorry which line is that? (All the xmlhttp is confusing me)
YsoL8
ooh I got it! If only I'd asked earlier
YsoL8