Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: AJAX Example - jQuery and JavaScript

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: Wed, Oct 22, 2008, 4:26 PM


The following is a sample HTML file that uses AJAX via the XMLHttpRequest object.

<html>
<head>
< script type="text/javascript">
function test()
{
    var div;
    div = window.document.getElementById("myDiv");
    div.innerText = "hello world";
}
var xmlhttp
function loadXmlDoc(url)
{
    xmlhttp = null

    //-- Mozilla, etc. ----------------------------------------------------------------
    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest()
    }
    //-- IE ---------------------------------------------------------------------------
    else if (window.ActiveXObject)
    {
        try 
        { 
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
        } 
        catch (e) 
        {
            try 
            { 
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
            } 
            catch (e) {}
        }
    }

    //-- Make AJAX call ---------------------------------------------------------------
    if (xmlhttp != null)
    {
        xmlhttp.onreadystatechange = state_Change
        xmlhttp.open("GET", url, true)
        xmlhttp.send(null)
    }
    //else
    //{
    //    alert("Your browser does not support XMLHTTP.")
    //}
}

function state_Change()
{
    if (xmlhttp.readyState == 4) // 4 = loaded
    {
        var div;
        div = window.document.getElementById("myDiv");

        if (xmlhttp.status == 200) // 200 = OK
        {
            // handle xmlhttp.responseText
            div.innerText = xmlhttp.responseText;
        }
        else
        {
            div.innerText = "Problem retrieving XML data"
        }
    }
}
</script>
</head>
<body>
<input type="button" value="test" 
onclick='loadXmlDoc("http://www.yahoo.com");' />
<div id="myDiv"/>

</body>
</html>

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.