1. file index.php
<h1>Javascript And JSON</h1>
<p>Here's a demo on how to use json and ajax for sending data to server</p>
<div id="form">
Name: <input type="text" id="name"/><br/>
City: <input type="text" id="city"/><br/>
Age: <input type="text" id="age"/><br/>
<input type="button" onclick="sendData()" value="Save"/>
</div>
<div id="response"></div>
<p>Here's a demo on how to use json and ajax for sending data to server</p>
<div id="form">
Name: <input type="text" id="name"/><br/>
City: <input type="text" id="city"/><br/>
Age: <input type="text" id="age"/><br/>
<input type="button" onclick="sendData()" value="Save"/>
</div>
<div id="response"></div>
<script>
function sendData(){
var name = document.getElementById('name');
var city = document.getElementById('city');
var age = document.getElementById('age');
var data = '';
var data = data + '<?xml version=\'1.0\'?>';
var data = data + '<data>';
var data = data + '<name>'+name.value+'</name>';
var data = data + '<city>'+city.value+'</city>';
var data = data + '<age>'+age.value+'</age>';
var data = data + '</data>';
var parser = new DOMParser();
var datas = parser.parseFromString(data,'text/xml');
var ajax = new XMLHttpRequest();
ajax.open("GET","hello.php?data="+data,false);
ajax.send();
name.value = '';
city.value = '';
age.value = '';
var res = document.getElementById('response');
res.innerHTML = ajax.responseText;
}
</script>
2. file: hello.php
<?php
$handle = mysql_connect("localhost","root","indonesia");
mysql_select_db("data",$handle);
$data = $_GET['data'];
$doc = new DOMDocument();
$xmlDoc = $doc->loadXML($data);
$lol = $doc->getElementsByTagName('name');
$name = $lol->item(0)->nodeValue;
$cities = $doc->getElementsByTagName('city');
$city = $cities->item(0)->nodeValue;
$ages = $doc->getElementsByTagName('age');
$age = $ages->item(0)->nodeValue;
echo $name." => ".$city." => ".$age;
$query = "INSERT INTO personal_info (name, city, age) VALUES ";
$query .= "('".$name."', '".$city."', ".$age.")";
$result = mysql_query($query);
?>
No comments:
Post a Comment