1

Currently I'm trying to populate a site dynamically. When I step through the code, it works perfect. However, when I run it on page load as intended, it doesn't work. The relevant code is:

<body onload="populate_all(string)";>

function populate_all(string)
{
  var split = string.split(" ");
  for(i = 0; i < split.length; i++)
  {
    populate(split[i], 'main'); 
  }
} 

function populate(string, location)
{
  if (string.length==0)
  { 
   document.getElementById(location).innerHTML="";
   return;
  }

  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)
  {
        var divTag = document.createElement("div");

        divTag.className ="info";

        divTag.innerHTML = xmlhttp.responseText;

        document.getElementById(location).appendChild(divTag);
  }
 }
 xmlhttp.open("GET","populate.php?string="+string,true);
 xmlhttp.send();
 }

I've read up on this issue enough to be pretty sure the php isn't the issue. Basically: I'm running a javascript function with AJAX several times in a loop and the code only works when I debug it. Thanks for the help!

1
  • Sorry, "it doesn't work" isn't real clear. Instead of creating the divs I want, which is several divs with different information, it creates either only the last div or four instances of the last div. Commented Apr 8, 2012 at 16:03

2 Answers 2

0
  1. Declare xmlhttp locally.
  2. Use a different variable name as location. location is a global variable, which holds properties and methods to manipulate the current location.

    function populate(string, s_location) {
        var xmlhttp;
    

Currently, you keep overwriting the xmlhttp variable in the populate method. As a result, the xmlhttp object points to the last request.

Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick! I love it when things are that simple. Thanks!
0

For me it was this: Use javascript variable outside success function

When making calls to $.getJSON etc, with the debugger attached it fixes/alters the timing and scoping. I was updating a table cell value from an xhr response fired by timed background events, and I needed to be doing the cell updates in the nested success functions. With the debugger attached things magically worked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.