Environmental Site Logo
 
Ajax Home
Ajax Example ASP
Ajax Example PHP
What is AJAX?
 
 

AJAX Example


In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a web form. Enter some lettrs in the text box below and see what happens after suggestions.

First Name:

Suggestions:


Explanations of the above Example

This example consists of one Form object, 3 JavaScript Functions (showHint(), stateChanged(), getXmlHttpObject()) and one getHint.asp file. The details of the form is given below:-

<form>
First Name:
<input type="text" id="txtSample"
onkeyup="showHint(this.value)"> </form>

<br>Suggestions: <span id="txtHints"></span>


Form Object

Above code is a simple HTML form with an input field called "txtSample".

An event attribute for the input field defines a function to be triggered by the onkeyup event. Next line below the form contains a span called "txtHints".

The span is used as a placeholder for data retrieved from the web server. When the user inputs data, a function called "showHint()" is executed.

The execution of the function is triggered by the "onkeyup" event. Each time the user moves his finger away from a keyboard key inside the input field, the function showHint is called.


showHint() Function

The showHint() function is a simple JavaScript function placed in between the <head> section of the page. The function contains the following lines:

function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHints").innerHTML=""
return
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="gethint.asp"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}



The function executes whenever a character is entered in the input field. If the text field is not empty (str.length > 0) the function executes the following:

Defines the url (filename) to send to the server
Adds a parameter (q) to the url with the content of the input field
Adds a random number to prevent the server from using a cached file
Creates an XMLHTTP object, and tells the object to execute a function -called stateChanged when a change is triggered
Opens the XMLHTTP object with the given url.
Sends an HTTP request to the server

If the input field is empty, the function simply clears the content of the txtHint placeholder.


More on this site
Agricultural Education
Environmental News
Funny SMS
Computers & Technical
Agri Search Engine
Funny Videos
Bollywood Celebrities
Funny Games
Help Children!
ASP Bulk Email
Secure a Job New!
Mother Teresa
Sex Education
 
Aishwarya Rai Movie Clip



© All rights reserved
Send your comments and suggestions to Webmaster. Best viewed in 800x600 with medium text size in Firefox 2