Pages

Wednesday, July 11, 2012

An Ajax basic sample Demo

Create a html document and save it as ajax_test.html

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>An Ajax basic sample Demo</title>

<!--Get Ajax objects from remote file-->
<script type="text/javascript" src="ajax_script.js"></script>
<style>
    #display{ color: #09F; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; font-size: 16px;}
</style>
</head>

<body>
<h2>An Ajax basic sample Demo</h2>

<button onclick="displayBlogName();">Display Blog name</button>
<br /><br />

<!--This div will render what has been typed by the use-->
<div id="display">
</div>

</body>
</html>

Create another file and save it as site_name.html. Save it in the same folder too.

<p>http://phpcodesamples.blogspot.com/</p>

Finally create an JavaScript file and name it ajax_script.js

// JavaScript Document

var xmlHttp = createXMLHttpRequest();

function createXMLHttpRequest()
{
    //Allow Ajax to work with Internet Explorer by using ActiveXObjects
    if(window.ActiveXObject){
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        return new XMLHttpRequest();
    }
}

function handleStateChange()
{
    if(xmlHttp.readyState == 4){
        if(xmlHttp.status == 200){
            document.getElementById('display').innerHTML = xmlHttp.responseText;
        }
    }
}


function displayBlogName()
{   
    //The url responsible for the data feed or processing
    var url = "http://localhost/samples/site_name.html";
    //Open the request Object
    xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = handleStateChange;
    //Send your request to the server
    xmlHttp.send(null);
    xmlHttp.close();
}

  As you will notice when you load ajax_test.html in your browser. The page will display the message in the site_name.html without conducting any page reload. This is the feature I was explaining earlier when introducing Ajax. I will be showing how the same can be achieved using PHP.


No comments:

Post a Comment