1. Create File index.php
<h1>Ajax And XML Demos</h1>
<div>Enter a name:
<input type="text" id="name_id"/>
<input type="button" onclick="getData()" value="Get Data"/>
</div>
Name: <span id="name"></span><br/>
City: <span id="city"></span><br/>
Age: <span id="age"></span><br/>
<script>
function getData(){
var name_d = document.getElementById('name_id');
var name = document.getElementById('name');
var city = document.getElementById('city');
var age = document.getElementById('age');
var ajax = new XMLHttpRequest();
ajax.open("GET","hello.php?name="+name_id.value,false);
ajax.send();
var data = ajax.responseXML;
name.innerHTML = data.getElementsByTagName('name')[0].childNodes[0].nodeValue;
city.innerHTML = data.getElementsByTagName('city')[0].childNodes[0].nodeValue;
age.innerHTML = data.getElementsByTagName('age')[0].childNodes[0].nodeValue;
}
</script>
<div>Enter a name:
<input type="text" id="name_id"/>
<input type="button" onclick="getData()" value="Get Data"/>
</div>
Name: <span id="name"></span><br/>
City: <span id="city"></span><br/>
Age: <span id="age"></span><br/>
<script>
function getData(){
var name_d = document.getElementById('name_id');
var name = document.getElementById('name');
var city = document.getElementById('city');
var age = document.getElementById('age');
var ajax = new XMLHttpRequest();
ajax.open("GET","hello.php?name="+name_id.value,false);
ajax.send();
var data = ajax.responseXML;
name.innerHTML = data.getElementsByTagName('name')[0].childNodes[0].nodeValue;
city.innerHTML = data.getElementsByTagName('city')[0].childNodes[0].nodeValue;
age.innerHTML = data.getElementsByTagName('age')[0].childNodes[0].nodeValue;
}
</script>
2. Create file: hello.php
<?php/**
* Assume the table structure is like this one
* CREATE TABLE personal_info
* (id INT NOT NULL AUTO_INCREMENT KEY,
* name CHAR(20) NOT NULL DEFAULT '',
* city CHAR(20) NOT NULL DEFAULT '',
* age INT NOT NULL DEFAULT 0
* );
*/
$handle = mysql_connect("localhost","root","indonesia");
mysql_select_db("data", $handle);
$name = $_GET['name'];
$name = urldecode($name);
$query = "SELECT * FROM personal_info WHERE name= '$name'";
$result = mysql_query($query);
$output = '<?xml version="1.0" ?>';
$output .= '<data>';
$output .= '<name>'.$name.'</name>';
while($row=mysql_fetch_array($result)){
$output .= '<age>'.$row['age'].'</age>';
$output .= '<city>'.$row['city'].'</city>';
}
$output .= '</data>';
header("Content-type: application/xml");
echo $output;
?>
No comments:
Post a Comment