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
<title>JSON Demo</title>

<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>

<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>

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



2. hello.php file

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

    $data = array(
        'name'=>'luna maya',
}else if(strcasecmp($namee,'lady')==0){
    $data = array(
        'name'=>'lady gaga',
        'city'=>'new york',
}else if(strcasecmp($namee,'bill')==0){
    $data = array(
        'name'=>'bill clinton',

echo json_encode($data);


No comments:

Post a Comment