delta one handle kitchen faucets

Home Ajax javascript examples
« Home »
Apr 6th, 2011 Comments: 0

Ajax javascript examples

Plurk
Share this

JavaScript

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>

<body>

 

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

<!–

//Support Code for Browser

function ajaxFunction(){

var ajaxRequest;  // This is necessary for AJAX

 

try{

// Firefox, Opera, Safari

ajaxRequest = new XMLHttpRequest();

} catch (e){

// Internet Explorer

try{

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

} catch (e) {

try{

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);

ajaxRequest.send(null);

}

 

//–>

</script>

 

<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>

</select>

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

</form>

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

</body>

</html>

This example will result in the following display:

Display: Max Age:

Sex:

M

F

 

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.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>