Hi i am new and i love this site
I am learning javascript and so far i have done a lot of tutorials but i can’t make ajax work.
I saw this on W3school
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
Now i changed one line to
xmlhttp.open("GET","ajax_info.php?day="+document.getElementById("day").value,true);
It should read info based on a day instead of all of the days.
Sometimes the page is empty, nothing happens, sometimes it works and everything is there.
To reproduce you can just hit F5 like 3 times in a row, it will fail at least once.
Please help me save the last bits of hair i still have !
The problem is caused by the script loading too fast that the “day” element is not there yet.
To fix you can simply add an event handler to wait for the document to load.
You can do this like that :
document.addEventListener("load", functionName, false);and then create a function that will hold the code you pasted here.The function will be called at the appropriate time and it should work.
Other than that, i would recommend using libraries like jQuery or MooTools as it makes it easier for your code to run across many browsers. In your code, you are checking to see which browser the user has to create the request..
With jquery you can do all your code with a single line of code like so:
You can learn more at http://www.jquery.com