Dynamic page element updates without reloading (using AJAX)
With this technique, you can update elements of a page with server-side data without reloading it (using the XMLHttpRequest object and Javascript).The technique is known as AJAX (Asynchronous JavaScript And XML). This code example is based upon the Mozilla Developer Center article AJAX: Getting started.
The code below have been tested succesfully in the top seven browsers used in the world, including the legacy IE6.
Try the code in a popup window.
This example consists of three files, one containing the client page (default.htm), one containing the code for server responses using HTTP GET (dataGET.asp) and one containing the code for server responses using HTTP POST (dataPOST.asp).
default.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Ajax programming</title>
</head>
<body>
<script type="text/javascript" language="javascript">
var http_request = false;
var ser = Math.round(Math.random()*1000000); // Anti-caching serial number
var debug = false; // Set to true to show the full server response
function ajax(httpRequestMethod, url, parameters, target)
{
http_request = false;
document.getElementById(target).innerHTML = 'Wait...'
if (window.XMLHttpRequest)
{ // For Mozilla, Safari, Opera, IE7
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/plain');
//Change MimeType to match the data type of the server response.
//Examples: "text/xml", "text/html", "text/plain"
}
}
else if (window.ActiveXObject)
{ // For IE6
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{}
}
}
if (!http_request)
{
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {updateElement(target);};
if (httpRequestMethod == 'GET')
{
http_request.open('GET', url + '?' + parameters, true);
http_request.send(null);
ser = ser + 1;
}
else if (httpRequestMethod == 'POST')
{
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
http_request.send(parameters);
}
else
{
alert('Sorry, unsupported HTTP method');
}
}
function updateElement(target)
{
if (http_request.readyState == 4)
{
if (debug == true)
{
alert(http_request.responseText);
}
if (http_request.status == 200)
{
document.getElementById(target).innerHTML =
http_request.responseText;
}
else if (debug == false)
{
alert('The server returned an error. Please set debug = true to see the full server response.');
}
}
}
</script>
<form name="f1" action="" onsubmit="return false;">
<input type="text" name="id" value="123" />
</form>
<span style="cursor: pointer; text-decoration: underline; color: #0000FF;"
onclick="ajax(
'GET',
'DataGET.asp',
'ser=' + ser + '&id=' + document.f1.id.value + '&somename=somevalue',
'dataBox'
)">
Send the data to the server (using the request method "GET") and update
the div with the response.</span>
<br />
<span style="cursor: pointer; text-decoration: underline; color: #0000FF;"
onclick="ajax(
'POST',
'DataPOST.asp',
'id=' + document.f1.id.value + '&somename=somevalue&so=on',
'dataBox'
)">
Send the data to the server (using the request method "POST") and update
the div with the response.</span>
<br />
<br />
<div id="dataBox" style="width:380px; border:solid black 1px; padding:2px;">
Div element. Content will be replaced by data from the server.
</div>
</body>
</html>
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Ajax programming</title>
</head>
<body>
<script type="text/javascript" language="javascript">
var http_request = false;
var ser = Math.round(Math.random()*1000000); // Anti-caching serial number
var debug = false; // Set to true to show the full server response
function ajax(httpRequestMethod, url, parameters, target)
{
http_request = false;
document.getElementById(target).innerHTML = 'Wait...'
if (window.XMLHttpRequest)
{ // For Mozilla, Safari, Opera, IE7
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/plain');
//Change MimeType to match the data type of the server response.
//Examples: "text/xml", "text/html", "text/plain"
}
}
else if (window.ActiveXObject)
{ // For IE6
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{}
}
}
if (!http_request)
{
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {updateElement(target);};
if (httpRequestMethod == 'GET')
{
http_request.open('GET', url + '?' + parameters, true);
http_request.send(null);
ser = ser + 1;
}
else if (httpRequestMethod == 'POST')
{
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
http_request.send(parameters);
}
else
{
alert('Sorry, unsupported HTTP method');
}
}
function updateElement(target)
{
if (http_request.readyState == 4)
{
if (debug == true)
{
alert(http_request.responseText);
}
if (http_request.status == 200)
{
document.getElementById(target).innerHTML =
http_request.responseText;
}
else if (debug == false)
{
alert('The server returned an error. Please set debug = true to see the full server response.');
}
}
}
</script>
<form name="f1" action="" onsubmit="return false;">
<input type="text" name="id" value="123" />
</form>
<span style="cursor: pointer; text-decoration: underline; color: #0000FF;"
onclick="ajax(
'GET',
'DataGET.asp',
'ser=' + ser + '&id=' + document.f1.id.value + '&somename=somevalue',
'dataBox'
)">
Send the data to the server (using the request method "GET") and update
the div with the response.</span>
<br />
<span style="cursor: pointer; text-decoration: underline; color: #0000FF;"
onclick="ajax(
'POST',
'DataPOST.asp',
'id=' + document.f1.id.value + '&somename=somevalue&so=on',
'dataBox'
)">
Send the data to the server (using the request method "POST") and update
the div with the response.</span>
<br />
<br />
<div id="dataBox" style="width:380px; border:solid black 1px; padding:2px;">
Div element. Content will be replaced by data from the server.
</div>
</body>
</html>
dataGET.asp:
<%
Option Explicit
If Len(Request.Querystring("id")) < 10 Then
If IsNumeric(Request.Querystring("id")) Then
If Clng(Request.Querystring("id")) = 123 Then
Response.Write("Hello world!")
Else
Response.Write("ID not found.")
End If
Else
Response.Write("Invalid input.")
End If
Else
Response.Write("Input too long.")
End If
%>
Option Explicit
If Len(Request.Querystring("id")) < 10 Then
If IsNumeric(Request.Querystring("id")) Then
If Clng(Request.Querystring("id")) = 123 Then
Response.Write("Hello world!")
Else
Response.Write("ID not found.")
End If
Else
Response.Write("Invalid input.")
End If
Else
Response.Write("Input too long.")
End If
%>
dataPOST.asp:
<%
Option Explicit
If Len(Request.Form("id")) < 10 Then
If IsNumeric(Request.Form("id")) Then
If Clng(Request.Form("id")) = 123 Then
Response.Write("Hello world!")
Else
Response.Write("ID not found.")
End If
Else
Response.Write("Invalid input.")
End If
Else
Response.Write("Input too long.")
End If
%>
Option Explicit
If Len(Request.Form("id")) < 10 Then
If IsNumeric(Request.Form("id")) Then
If Clng(Request.Form("id")) = 123 Then
Response.Write("Hello world!")
Else
Response.Write("ID not found.")
End If
Else
Response.Write("Invalid input.")
End If
Else
Response.Write("Input too long.")
End If
%>