AJAX - Request a Server
AJAX - Sending a request to a server
To send off a request to the server, we use the open() and send() methods.
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 ASP file are in the same directory, the code would be:
xmlhttp.open("GET","time.asp",true);
xmlhttp.send(null); |
Now we must decide when the AJAX function should be executed.
We will let the function run "behind the scenes" when a user types something in the
"Name" field:
<form name="myForm">
Name: <input type="text" name="username"
onkeyup="ajaxFunction();" />
Time: <input type="text" name="time" />
</form> |
Our updated "testAjax.htm" file now looks like this:
<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.myForm.time.value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","time.asp",true);
xmlhttp.send(null);
}
</script>
<form name="myForm">
Name: <input type="text" name="username" onkeyup="ajaxFunction();" />
Time: <input type="text" name="time" />
</form>
</body>
</html> |
The next chapter makes our AJAX application complete with the "time.asp" script.
Click here to design a Stunning Flash Website for Free
Wix is a revolutionary web design tool that provides anyone with the possibility to create professional and beautiful websites for free.
With e-commerce features, search engine visibility and many more professional tools, Wix is the ultimate solution for creating a spectacular site while saving tons of money.
|