ldoroni
ldoroni

Reputation: 103

the code of ajax dont work

first of all, sory for my english...

someone can help me understend why the code dont work?

i hope you'll be able to figure out what the problem was, I had a little hard to explain


this is the codes:

<!--- func 0 --->
<script>
function refresh(name, url, info, type)
{
var str;
if (type=="send") {
str = document.forms["aaa"]["txt"].value;
}
if (type=="send" && str=="")
  {
  document.getElementById(name).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)
    {
    document.getElementById(name).innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET",url+"?info="+str,true); // send the text to page
xmlhttp.send();  
return false;
}
</script>
<!--- end - func 0 --->


<!--- func 1 --->
<script type="text/javascript">
setInterval("refresh('bbb', 'refresh.php', '', 'refresh')", "1000");
</script>
<div id='bbb'> div to refresh at 1000 ms </div>
<!--- end - func 1 --->


<!--- func 2 --->
<form name='aaa' onsubmit="return refresh('aaa', 'send.php', '', 'send');" method='post'>
txt: <input type='text' name='txt' autofocus='autofocus'> <input type='submit' value=' send '>
</form>
<div id='aaa'> div that <b>*send*</b> txt to sql </div>
<!--- end - func 2 --->

Upvotes: 1

Views: 86

Answers (2)

Bergi
Bergi

Reputation: 664207

Because you have only one global xmlhttp variable. If you put both functions on the page, it can happen that they try to send two requests in parallel which will then interfere. Make it a local variable:

var xmlhttp = …

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

The main problem is that xmlhttp is being defined as a global variable, so if you happen to have two AJAX queries loading at the same time, they will interfere with each other. Use var xmlhttp to fix this.

That being said, you shouldn't support IE6 and even less so IE5. Just do this:

var xhr = new XMLHttpRequest();
xhr.open("GET",url+"?info="+str,true);
xhr.onreadystatechange = function() {
  if( this.readyState == 4 && this.status == 200) {
    document.getElementById(name).innerHTML = this.responseText;
  }
};
xhr.send();

Upvotes: 2

Related Questions