AJAX & Prototype Page 3 - Ajax Features Needed to Build Active Client Pages |
The data sent back from the server can be retrieved with the responseText property of the XMLHttpRequest object. This is a sample code. xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { Some HTML Value or JavaScript Property = xmlHttp.responseText; //You may call another function to do initialization. } } Sending a Request to the Server To send off a request to the server, we use the open() method and the send() method. The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server. If we assume that the HTML and the server executable file (e.g. sendText.pl that is called by the request) are in the same directory, the code would be: xmlHttp.open("GET","sendText.pl",true); xmlHttp.send(null); The send method sends the request to the server with a "data" parameter specifying the body of the request. For "GET" requests, this parameter should be a value of null, while for "POST" requests, it should be the parameters of the request. This method typically should always be called last. Now we must decide when the AJAX function should be executed. This is executed normally when an event is triggered. The following is a sample code that illustrates everything I have said about Ajax. There is an HTML button. When you click it some text will be sent from the server. The value of the onclick attribute is “ajaxFunction();”. When this function is called, it declares the XMLHttpRequest Object (variable). It performs the trials to assign the object variable. Next it stores the function that will process the response to onreadystatechange property of the object. This function is not executed at this point. It is executed only when the status of the readyState property changes. So it can only be executed after the open() and send() methods of the object have been called. Next, in the ajaxFunction() function, the open() and send() methods are called. <html> <head> <script type="text/javascript"> function ajaxFunction() { var xmlHttp; 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!"); } } } xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.getElementById('IDDIV').innerHTML = xmlHttp.responseText; } } xmlHttp.open("GET","sendText.pl",true); xmlHttp.send(null); } </script> </head> <body> <div id="IDDIV"> </div> <button type="button" onclick="ajaxFunction();">Obtain Data from Server</button> </body> </html>
blog comments powered by Disqus |
|
|
|
|
|
|
|