GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Tuesday, March 8, 2011

JS - Ajax Response As JSON


/**
 * This program is a demos on how to retrieve data using ajax
 * in JSON format. 
 * The process is simple. You create an array in PHP as what the
 * data you want to transfer it to the client. Next, handle the 
 * request using var data = eval('('+ajax.reponseText+')'). 
 * After this one,  you can process the data as object literal
 * in Javascript.
 * Please note, the eval function is the most important!
 * var data = eval('('+ajax.responseText+')');
 * or
 * var data = null;
 * eval("data = "+ajax.responseText);
 * or
 * var data = new Function("return "+ajax.responseText);
 */

1. index.php file
<html>
<head>
<title>JSON Demo</title>

</head>
<body onload="getData(document.getElementById('select').value)">
<h1>JSON Demo</h1>
<select id="select" name="namee" onchange="getData(this.value)">
<option value="luna">Luna</option>
<option value="lady">Lady Gaga</option>
<option value="bill">Bill Clinton</option>
</select>

<p>Name: <span id="name"></span></p>
<p>City:  <span id="city"></span></p>
<p>Age:  <span id="age"></span></p>
<p>Response: <span id="response"></span></p>

<script>
function getData(value){
    var ajax = new XMLHttpRequest();
    var name = document.getElementById('name');
    var city = document.getElementById('city');
    var age = document.getElementById('age');
    ajax.open("get","hello.php?namee="+value,false);
    ajax.send();
    var data = eval('('+ajax.responseText+')');
    var response = document.getElementById('response');
    name.innerHTML = data.name;
    city.innerHTML = data.city;
    age.innerHTML = data.age;
}

</script>

</body>
</html>



2. hello.php file
<?php

$namee = $_GET['namee'];
$data = array();

if(strcasecmp($namee,'luna')==0){
    $data = array(
        'name'=>'luna maya',
        'city'=>'denpasar',
        'age'=>27
    );
}else if(strcasecmp($namee,'lady')==0){
    $data = array(
        'name'=>'lady gaga',
        'city'=>'new york',
        'age'=>24
    );
}else if(strcasecmp($namee,'bill')==0){
    $data = array(
        'name'=>'bill clinton',
        'city'=>'virginia',
        'age'=>55
    );
}

echo json_encode($data);

Share/Bookmark

No comments:

Post a Comment