PDA

View Full Version : How to get information using XMLHttpRequest on page load?


gamestoenjoy
01-28-2010, 07:07 PM
Hi,

I am currently learning AJAX, and I want to write an simple example program (it is only for practice, it has no real meaning).

The program sends request to to PHP and gets response from it, then it should write the response using message box, all should happen on page load.
I wrote the following code:

function init(){
myRequst = new XMLHttpRequest();
var url = "http://localhost/dummy.php";
myRequst.open("GET",url,false);
myRequst.send(null);
var data = myRequst.responseText;
alert(data);
}

window.onload = init;


My PHP:

<?php
echo "Hello World";
?>


I don't see any message box when the page loads.
When using it after the page loaded with other events (not onLoad), it works and I see the message box with the response.

Can you please asisst me here.
How can I get the data on page load using XMLHttpRequest?

Thanks in advance :)

A1ien51
01-29-2010, 10:36 PM
The browser is?
Do you see errors in the console?

Eric

gamestoenjoy
01-30-2010, 04:36 PM
The browser is?
Do you see errors in the console?

Eric

Tried it on IE and FF.
There are no error in the console.

gamestoenjoy
01-31-2010, 04:14 PM
I finally solved it

The following code works:

window.onload = function(){
var myRequst = new XMLHttpRequest();
var url = "http://localhost/dummy.php";
myRequst.open('get', url);
myRequst.onreadystatechange = function(){
if ((myRequst.readyState == 4) && (myRequst.status == 200)){
alert(myRequst.responseText);
}
}
myRequst.send(null);
}


Thanks for your help.