Graham T
Graham T

Reputation: 966

Error passing clicked element's ID with AJAX

I'm trying to pass the ID of a clicked DIV to a particular function and I've run into an odd result. The ID makes it successfully to the function, as the Error State is fired (ajax-loader.gif), and populates itself within the DIV the onclic was initiated from.

However, I don't see why the AJAX is returning a non-completed Ready-State. If I replace the 'clicked_id' with the hardcoded name of the ID, it works correctly. However it's proven that the ID name is making it to the function correctly, as the Error event is being populated in the provided ID's innerHTML.

I'm stumped. Any ideas? I'm sure this is a noob mistake, but I can't spot it.

I've initiated a new XMLHTTPRequest in my script, I just left it out for brevity. And I know there's probably easier way's to do this, like jQuery's click event, but for my own sake I want to know why this is broken.

<div class='colour'><img src='media/recipe_save.jpg' id='showtime' onclick='javascript:getServerTime(this.id);'></div>

function getServerTime(clicked_id) {
  var thePage = 'ajax.recipesave.php';
  myRand = parseInt(Math.random()*999999999999999);
  var theURL = thePage +"?rand="+myRand;
  myReq.open("GET", theURL, true);
  myReq.onreadystatechange = theHTTPResponse(clicked_id);
  myReq.send(null);
}

function theHTTPResponse(clicked_id) {
  alert(clicked_id);
  if (myReq.readyState == 4) {
    if(myReq.status == 200) {
       var timeString = myReq.responseXML.getElementsByTagName("timestring")[0];
       document.getElementById(clicked_id).innerHTML = timeString.childNodes[0].nodeValue;
    }
  } else {
    document.getElementById(clicked_id).innerHTML = '<img src="media/ajax-loader.gif"/>';
  }
}

Upvotes: 0

Views: 249

Answers (1)

jfriend00
jfriend00

Reputation: 707546

myReq.onreadystatechange needs to be assigned a function reference. You can't assign it the result of executing a function and that's what you're doing with this line:

myReq.onreadystatechange = theHTTPResponse(clicked_id);

This is immediately executing theHTTPResponse(clicked_id) and assigning the result (which is undefined) to myReq.onreadystatechange. Thus, you end up with no callback for onreadystatechange.

Change the above line to this:

myReq.onreadystatechange = function() {theHTTPResponse(clicked_id)};

This way, you're assigning an actual function to onreadystatechange and this function will get called when the state changes rather than immediately.

Upvotes: 1

Related Questions