Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Thursday, June 6, 2013

AJAX - Parse XML result

In previous example, we got response as plain text.
//
document.getElementById("result").innerHTML = xmlhttp.responseText;
//

Today, we would like to get and parse XML response with AJAX.
See employee.xml

    
        Mike
        20
        mac
        iphone
        ipad
    
    
        James
        25
        mac
        iphone
        ipad
    
    
        Judy
        18
        mac
        iphone
        ipad
    



AJAX code
function getResult() {
    var xmlhttp = new XMLHttpRequest();
    var name = document.getElementById("name").value;
    
    xmlhttp.onreadystatechange = function() {   
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            // get root element
            var root = xmlhttp.responseXML.documentElement;
            // get all employee emelemts
            var employees = root.getElementsByTagName("employee");
            var name = "";
            var age = undefined;

            var output = "";
            
            // get name and age for each employee element
            for (var i = 0; i < employees.length; i++) {
                name = employees[i].getElementsByTagName("name");
                age = employees[i].getElementsByTagName("age");
                output += name[0].firstChild.data + " is " + age[0].firstChild.data + ".";
            }
     
            document.getElementById("result").innerHTML = output;
        }
    }
   
    xmlhttp.open("GET", "employee.xml");
    xmlhttp.send();
}


jQuery implementation
function getResult() {
    $.ajax({
        url: 'employee.xml',
        dataType: 'xml',
                
        success: function(data) {
            $('#result').text("");
            $(data).find('employees employee').each(function() {
                var name = $(this).find('name').text();
                var age = $(this).find('age').text();
                var id = $(this).attr('id');
                var asset = $(this).find('asset').eq(0).text();
                        
                $('#result').append(
                    $('<div />', {
                        text: '(' + id + ') ' + name + ' is ' + age +
                              ' - ' + asset + '.'
                    })
                );
            })
        },
                
        error: function() {
            $("#result").text("failed to load.");
        }
    });
}

Result




AJAX - Request MySQL data through PHP

Suppose we need to get password (actually hash value in database) of a specified user, how we can make that?

We have a form to get user name input and have a button associated with function getResult().
 

getResult()
function getResult() {
    var xmlhttp = new XMLHttpRequest();
    var name = document.getElementById("name").value;
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            setTimeout(function() {document.getElementById("result").innerHTML = xmlhttp.responseText;}, 1000);
        } else {
            document.getElementById("result").innerHTML = "Loading...";
        }
    }
   
    xmlhttp.open("POST", "getuserhash.php");
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("name=" + name);
}

getuserhash.php
include_once('connection.php');

$name = $_POST['name'];

$query = $pdo->prepare("SELECT user_password FROM user WHERE user_name = ?");
$query->bindValue(1, $name);
$query->execute();
$data = $query->fetch();

echo $data["user_password"];

It works!







Use jQuery to rewrite getResult()
        
function getResult() {
    var name = $("#name").val();
    $.post("getuserhash.php", {name:name}, 
        function(data) {
            $("#result").html(data);
        }
    );
}

Wednesday, June 5, 2013

AJAX - First Sample

AJAX, a.k.a Asynchronous JavaScript and XML. According to the name, we can feel it is not a new technology, but something JavaScript and XML related. AJAX is actually a new way of exchanging data using current standards. AJAX allows user to request only necessary data from the server and update the data on page, so we don't have to reload the whole page.

So let us see a simplest sample
    

    AJAX Sample




Several interesting things in above code.

XMLHttpRequest
It is used to send HTTP and HTTPS requests to the server and load response data. The data could be received from the server as JSON, XML, HTML or plain text. In our example, it is plain text.
xmlhttp.open
The requests must be initialized through the open method. It has five parameters in total (Method, URL, Asynchronous, UserName, Password) and only the first two are required. Supported methods could be GET, POST, HEAD, PUT, DELETE and OPTIONS. Asynchronous has two Boolean values, and true is the default one. False will block execution of the current script until the request has been completed, thus not invoking the onreadystatechange event listener.
xmlhttp.send
Send the request and you can specify a string data for and only for POST request.
xmlhttp.onreadystatechange
It is a event listener and will be automatically invoked when readyState property of the XMLHttpRequest object is changed.
xmlhttp.readyState
equals 1 after open has been invoked successfully
equals 2 after send has been invoked and response head has been received
equals 3 after response starts to load
equals 4 after response has finished loading
If you would like to see how the readyState is changed, try below code
    
if (xmlhttp.readyState == 1) {
    document.getElementById("result").innerHTML = xmlhttp.readyState;
} else if (xmlhttp.readyState == 2) {
    var state = xmlhttp.readyState;
    setTimeout(function() {document.getElementById("result").innerHTML = state}, 2000);
} else if (xmlhttp.readyState == 3) {
    var state = xmlhttp.readyState;
    setTimeout(function() {document.getElementById("result").innerHTML = state}, 4000);
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var state = xmlhttp.readyState;
    setTimeout(function() {document.getElementById("result").innerHTML = state}, 6000);
    setTimeout(function() {document.getElementById("result").innerHTML = xmlhttp.responseText;}, 8000);
} else {
    document.getElementById("result").innerHTML = "Failed to load.";
}