-
page onload problem
hey,
I am trying to get ajax to get values from a jsp page when the html loads, but first time the page loads, it gives me an error saying "The data necessary to complete this operation is not yet available" for the xmlHTTPRequest.responseText but when i refresh the page, it loads perfectly! jsp tested and works so the problem resides in my ajax/html file.
heres the html:
Code:
<html>
<head>
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
var optionID;
//generic code (www.w3schools.com)
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest(); }
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
//problem
var url="get.jsp?name=";
xmlHttp.open("GET", url,true);
xmlHttp.send(null);
var getVal = xmlHttp.responseText;
alert(getVal);
document.getElementById("myForm1").innerHTML=getVal;
}
</script>
</head>
<body onLoad="ajaxFunction()">
<table name="mytable" cellspacing="10">
<tr>
<td>
<form name="myForm" id="myForm1">
</form>
</td>
<td>
</td>
</tr>
</table>
</body>
</html>
-
You missed the important part:
after initialization there is a need to assign a processing function with onreadystatechange property. After sending You have to wait for a page to load, finish and return data. That is achieved with readyState and status properties.
Thus Your code should look like this:
//problem
if(xmlHttp){
xmlHttp.onreadystatechange = process; // assign a processing function
var url="get.jsp?name=";
xmlHttp.open("GET", url,true);
xmlHttp.send(null);
}
}
function process(){
// Now wait for page to be executed and return data
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)){
// everything is OK, do the job
var getVal = xmlHttp.responseText;
alert(getVal);
document.getElementById("myForm1").innerHTML=getVal;
}
}