Yash Sodha
Yash Sodha

Reputation: 703

XMLHttpRequest output not shown

Here is my JavaScript function:-

Solved JavaScript function:-

function delfile(fileid) {
  var div = "fileid_" + fileid;
  var location = "/delfile/" + fileid;
  if (window.XMLHttpRequest)
  {
    var xmlhttp=new XMLHttpRequest();
  } 
  else
  {
    var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    {
      document.getElementById(div).innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("POST", location, true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("");
}

Here is what I generate from PHP:-

echo "<td><div id='fileid_{$id}'><button onclick='delfile({$id})'>Delete File</button></div></td>";

My problem is that when user clicks on 2-3 links simultaneously, the http requests are sent via javascript and the files are deleted on the server but the div id's are not updated with the output of the http-request. Only the button on which the user last clicked gets the output of the http-request.

There is absolutely no problem in the PHP script, I just gave it for reference. The delfile script just sends "File Delted".

Solved by using local variables as suggested by @torazaburo.

Upvotes: 0

Views: 89

Answers (1)

user663031
user663031

Reputation:

You've failed to declare xmlhttp local to the function, which means it's shared among multiple requests, which is a recipe for disaster.

While you're at it, please also declare $div and $location local to the function. Also, please remove the $ prefix to those variable names, as this practice is known to rot the brain.

Your failure to declare the variables would have been picked up if you had put a "use strict;" at the top of your function, as you should.

Upvotes: 1

Related Questions