Prerequisites:
- Knowledge of HTML
- At least basic knowledge of JavaScript
- Server-side coding knowledge, PHP, ASP, etc..
Step 1 - HTML
In this tutorial we are going to setup a div with an id of ajaxout, to display the retrieved MD5. The script will update the contents of ajaxout using innerHTML.
<div id="ajaxout"></div>
We are also going to need a form, which will allow the user to submit their information.
<form name="ajax" onsubmit="sndReq(document.ajax.str.value); return false;"> <input name="str" type="text" /><input type="button" value="Retrieve MD5" onclick="sndReq(document.ajax.str.value); return false;" /> </form>
Step 2 - JavaScript Setup
The XMLHttpRequest object will be used to retrieve the page with the required information. IE will use MS's ActiveX object.
function requestObj() {
var reqObj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
reqObj = new ActiveXObject("Microsoft.XMLHTTP");
}else{
reqObj = new XMLHttpRequest();
}
return reqObj;
}
var http = requestObj();Next, a function must be created to use the newly created object and retrieve the desired page. I added a loading message.
function sndReq(action) {
document.getElementById("ajaxout").innerHTML = "Loading...";
http.open('get', 'md5.php?str='+action, true);
http.onreadystatechange = handleResponse;
http.send(null);
}The following code is executed when the http object's state changes. It checks for a readystate of 4 (request complete), and the ajaxout div is updated with the response.
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById("ajaxout").innerHTML = response;
}
}Step 3 - Server-side Setup
The file we are retrieving in the previous step was called md5.php. For the purpose of this tutorial, the script simply outputs the MD5 hash of the input string:
<?php echo md5($_GET['str']); ?>
And that's really all there is to it!
Here it is, all put together: AJAX Basics Tutorial Example
Copyright 2008 Nathan LaPierre. For publication only on NovaTechForums.com.


Help





Promote to Article





















