Ajax javascript examples


In order to use AJAX to update a segment of a web page without having to reload the entire page, a JavaScript property known as innerHTML is typically used.  For this example, this attribute must be update when execution of the ajax-sample.php script is complete.

The first step is to create a new div on the page where the results of the query will be contained.   Once that is in place, the div’s innerHTML attribute can be updated with the information returned by ajax-sample.php. Don’t forget that the result is stored in ajaxRequest.responseText.  The following example demonstrates how this is done.

Example: <html>



<script language=”javascript” type=”text/javascript”>


//Support Code for Browser

function ajaxFunction(){

var ajaxRequest;  // This is necessary for AJAX



// Firefox, Opera, Safari

ajaxRequest = new XMLHttpRequest();

} catch (e){

// Internet Explorer


ajaxRequest = new ActiveXObject(“Msxml2.XMLHTTP”);

} catch (e) {


ajaxRequest = new ActiveXObject(“Microsoft.XMLHTTP”);

} catch (e){

// Something is incorrect

alert(“Current browser does not work.”);

return false;




// Function to receive data from server

ajaxRequest.onreadystatechange = somefunction(){

if(ajaxRequest.readyState == 4){

var ajaxDisplay = document.getElementById(‘ajaxDiv’);

ajaxDisplay.innerHTML = ajaxRequest.responseText;



var age = document.getElementById(‘age’).value;

var sex = document.getElementById(‘sex’).value;

var queryString = “?age=” + age + “&sex=” + sex;

ajaxRequest.open(“GET”, “ajax-example.php” + queryString, true);







<form name=’someForm’>

Max Age: <input type=’text’ id=’age’ /> <br />

<br />

Sex: <select id=’sex’>

<option value=’M’>m</option>

<option value=’F’>f</option>


<input type=’button’ onclick=’ajaxFunction()’ value=’Query MySQL’ />


<div id=’ajaxDiv’>Result displays here</div>



This example will result in the following display:

Display: Max Age:





Result displays here


If it is necessary to update a non form element, remember to use the innerHTML attribute that is associated with all HTML elements.   Also, remember that an HTML element can be accessed by giving it an id and using the document.getElementById function in JavaScript.

This entry was posted in Ajax Tutorials and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.