Tuesday, November 12, 2013

AJAX crash course


Ajax is a powerful technology and it’s also really easy to code (probably this is the reason why often webmasters abuse of it). The general concept it’s easy: you have a program or scriptthat can dinamically produce some output of interest. You have a web page, that will embed this output inside of it, without refreshing. The magic is made with a new JavaScript object called HTTPRequest.
The program: let’s take a simple script, called hello.php, that takes as input a string (name) and writes out: “Hello, name!”. Not so cool, but it’s just a demo, and the code is:
<? $name = $_GET['name'];
echo "Hello, <strong>$name</strong>!<br>"; ?>
The webpage: let’s suppose we want to put a hello in a <div> element. To identify it we’ll use the id property, like this <div id="hello>Loading...</div>. Then we can make our first JavaScript for AJAX. Three minimal elements are required: creating the RequestObject (copy and paste it!), a function that calls an external script through this object, and finally a function that is activated when the answer of the external scripts arrives! Here you are:
// Initialization of RequestObject
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();    }
    return ro;}
var http = createRequestObject();

/* Send request to PHP script */
function hello(name) {
    http.open('get', 'hello.php?name='+name);
    http.onreadystatechange = handleResponse;
    http.send(null);}

/* Manage received response */
function handleResponse() {    
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();
        if(response.indexOf('|' != -1)) {
            document.getElementById('hello').innerHTML = response;
        }
    }
}
Then we need to call the hello(name) function some how… we could start even like this: <a href="javascript:hello('proch');">Click here to say hello!</a>. Or something a little bit more interactive…