go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  AJAX Example -- AJAX Suggest on the client side: suggest.html
 
Subject: AJAX Example -- AJAX Suggest on the client side: suggest.html
Author: WebSpider
In response to: Step 4) Fire the ball
Posted on: 11/11/2009 01:26:02 PM

Now it's time to put all above together to show how a client side AJAX application looks like. A perfect example of AJAX is Google's Suggest -- a list of hints pop up while you are typing in the Google search box. Here a very silimar example (suggest.html) is shown to demostrate how AJAX make it work behind the scene.

<html>
<head>
<title>An example to show how AJAX works</title>
</head>

<body>

<script language="javascript">

var xmlhttp

function fireAJAX(str)
{
    // avoiding bothering the server too much
    if (str.length==0)
    {
        document.getElementById("myHook").innerHTML="";
        return;
    }
    
    // get an XMLHttpRequest object
    xmlhttp = getXmlHttpObject();
    
    if(xmlhttp==null)
    {
        alert ("Your browser does not support XMLHttpRequest!");
        return;
    }

    // register the lister before sending out the request
    xmlhttp.onreadystatechange = listenerForStateChange;

    // URL to the target server for response
    var url = "suggest.jsp?s=" + str;
    url = url + "?sid=" + Math.random();   // to avoid cached results

    // send out the request
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);    
}

function listenerForStateChange()
{
    if(xmlhttp.readyState==4)
    {
       document.getElementById("myHook").innerHTML = xmlhttp.responseText;
    }else{
       // do some funcy thing 
    }
}

function getXmlHttpObject()
{
    if (window.XMLHttpRequest)
    {
        // for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject)
    {
        // for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}
</script>

<form> 

Name: <input type="text" onkeyup="fireAJAX(this.value);" />  
Suggestions: <span id="myHook">This part will be soon replaced 
by response from server.</span>

</form>

</body>
</html>




 

> On 11/10/2009 10:30:59 PM WebSpider wrote:

Now you just need a event to trigger the AJAX action.

<html>
<body>

<form> 

Name: <input type="text" id="myID" onkeyup="fireAJAX()" />
Suggestions: <span id="myHook">This part will be soon replaced
 by response from server.</span>

</form>

</body>
</html>






References:

 


 
Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.