Sunny Books
What we have

AJAX and Prototype AJAX

AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page. This article talks about the original AJAX and AJAX of Prototype, another javascipt framework.

The AJAX basic

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
// call back function
    //document.getElementById("p_view").innerHTML=xmlhttp.responseText;
    $('p_view').update(xmlhttp.responseText);
    }
  }
xmlhttp.open("GET",site_url,true);
xmlhttp.send();



Prototype AJAX

The Prototype framework improves Ajax calls in a manner that is both easy and compatible with all modern browsers. Actual requests are made by creating instances of Ajax.Request.

Ajax.Request

var site_url = "http://"+url+"/send_suspicious.php?id="+id;
var aj = new Ajax.Request(  
    site_url, {  
    // method:'get',   // optional
    //parameters: id,   // if method is post, need parameters ?????
    onComplete: function(response) {
        $('myDiv').update(response.responseText);
    }
    
    }  
);

Using Ajax.Updater

The Ajax.Updater class is an extension of the normal Ajax.Request class, specifically used to update a DOM element with whatever content is returned from the HTTP sub-request. The alternative would be to use Ajax.Request yourself directly, then manually handle the response and update the required element accordingly.

Example

new Ajax.Updater($('myDiv'),site_url,{asynchronous:true});




Get or Post?

GET is simpler and faster than POST, and can be used in most cases. However, always use POST requests when:

  • A cached file is not an option (update a file or database on the server)
  • Sending a large amount of data to the server (POST has no size limitations)
  • Sending user input (which can contain unknown characters), POST is more robust and secure than GET
SUNWEB EXPERT