AJAX Hello World
AJAX and WEB2.0 are the new buzzwords for web developers. And you can get a lot of data and sample code for AJAX by doing a web search.
But if you are looking for a very simple hello world type AJAX sample code which is easy to understand, then here it is. Its around 50 lines of javascript and few lines of PHP script.
Say Hello to Server
The data from the server will go here...
Here is the source for the above demo:
test.html
ajax.js
servertime.php
And this is what happens in dozen easy steps:
# source file function explanation
1 test.php onClick() The button has onclick="talktoServer()"
2 ajax.js talktoServer() Button click calls talktoServer()
3 ajax.js talktoServer() Creates a new XMLHttpRequest()
3 ajax.js talktoServer() Register the function updateMsgOnBrowser() as a callback handler
4 ajax.js talktoServer() Do a POST request on servertime.php ( servertime.php?msg=Hello AJAX )
5 servertime.php Get the POST message
6 servertime.php Set the content header to application/xml
7 servertime.php Print out the XML data with server ip, timestamp and the message
8 ajax.js updateMsgOnBrowser() The callback handler is called with the XML data (testXML)
9 ajax.js updateMsgOnBrowser() get the XML elements (test, ip, message)
10 ajax.js updateMsgOnBrowser() get attributes (timestamp) and values (ip_value, msg_value) from XML elements
11 ajax.js updateMsgOnBrowser() get the document elemnt to update the result ( message_display)
12 ajax.js updateMsgOnBrowser() update with the new data (ip, timestamp, message )
You can see the XML data send send from the server by calling servertime.php directly as follows:
http://www.hackorama.com/ajax/servertime.php?msg=Hello%20AJAX
And this is the XML printed out by servertime.php
< ?xml version= "1.0" ? >
< test timestamp= "1128303298" >
< ip > 65.19.164.50< /ip >
< message > Hello Ajax< /message >
< /test >