AJAX sending data
We have created the AJAX object, and the form to retrieve the data from the web server using AJAX, now how do we actually get that data? To do so, we will have to use a few special methods.
This lesson focuses on:
- The open() method
- The send() method
- A complete AJAX example
The open() method
The open() method is used to get the server side script that will be used in an AJAX application.
This method takes three parameters:
Method
Specifies the method by which to get the script. Can take the value of "GET" or "POST"
URL
The URL of the script
Asynchronous
Takes the value of "true" or "false" specifying if the request should be handled asynchronously
Syntax:
ajaxObject.open(Method, URL, Asynchronous);
Example:
ajaxObject.open("POST", "advice.php", true);
The send() method
The send() method sends the actual request to the server. It should contain the value "null"
Example:
ajaxObject.send(null);
A complete AJAX example
The following is a complete AJAX example. Enter your name into the first text box, and the second text box will display some text automatically. The AJAX will get the data from the file advice.php
The code that makes this possible:
<html>
<head>
<title>AJAX!!</title>
<script type="text/javascript">
function ajaxDataGet(){
var ajaxObject; //the variable that will store the object
try{
// Opera 8.0+, Firefox, Safari, Netscape 7
ajaxObject = new XMLHttpRequest();
}
catch (e){
// Internet Explorer
try{
ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
//if the above ActiveXObject did not work
try{
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
//if AJAX is not supported at all
alert("Your browser does not support AJAX!! How is it back in 1998?");
return false;
}
}
}
//receive information returned by the webserver
ajaxObject.onreadystatechange=function(){
//if the request is complete
//update the "advice" field with
//the value returned from the AJAX object
if(ajaxObject.readyState==4){
document.formOne.advice.value=ajaxObject.responseText;
}
}
//use the GET method to open
//a file named "advie.php" asynchronously
ajaxObject.open("GET","advice.php",true);
//send the request to the server
ajaxObject.send(null);
}
</script>
</head>
<body>
<form name="formOne">
<p>
Name:
<br />
<input type="text" name="name" onkeyup="ajaxDataGet()" />
</p>
<p>
Advice:
<br />
<input type="text" name="advice" />
</p>
</form>
</body>
</html>
The code from advice.php:
<?php echo "AJAX is cool! Use it!"; ?>




