Monday, September 6, 2010

Ajax Example

<html>
    <head>
    <title></title>
    <script type="text/javascript">
      
        if(window.ActiveXObject)
        {
        xmlhttp = new ActiveXObeject("MSxml2.XMLHTTP");
        }
        else if(window.ActiveXObject)
        {
        xmlhttp = new ActiveXObeject("Microsoft.XMLHTTP");
        }
        else if(window.XMLHttpRequest)
        {
        xmlhttp = new XMLHttpRequest();
        }
function loadXMLDoc()
        {
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 )
            {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","/ajax_info.php",true);
        xmlhttp.send(null);
        }
    </script>
    </head>
    <body>

    <div id="myDiv"><p>Ajax comes here<p>
       
    </div>
    <input  type="submit" value="Click" name="submit" onclick="loadXMLDoc()">

    </body>
</html>


Explanation: First u have check that,if the browser supports ajax or not , for that there is the code above ,which is inside the script tag and then create a function with loadXMLDoc() ,
1.when the user clicks on submit button the function gets called 2.onreadystatechange is typical the event handler that triggers or call the javascript function ,  and it fires at every state change
3. readystate  --- > it is the state request , set equal to 4 means that the request and response is loaded asynchronously  from server and it is complete
4 .There  are 0,1,2,3,  0-> unintialized

1-->loading
2---> loaded

3--> interactive

4---> complete


create a a file called ajax_info.php ,in the just echo something so that the user clicks the submit button the ajax_info .php file is loaded under the div part without a page refresh , Here GET is the request , where we r getting the information , and t should be true because the data is transforming asynchronously.

No comments:

Post a Comment