Thursday, March 10, 2011

AJAX AND JSON - Sending Data

Here's a demo on how to send data from client to server:
In the client side, the steps are:
1. You get the data using Javascript DOM
2. Then you convert it to Javascript object literal
3. Then you change the object literal to string - JSON.stringify(data)
4. Then you send it through ajax

In the server side:
1. Catch the json data as a like $data = $_POST['data'];
2. Convert the data as an array $data = json_decode($data,true);

The Files:
a. 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"/>


function sendData(){
    var name = document.getElementById('name');
    var city = document.getElementById('city');
    var age = document.getElementById('age');
    var data = {}; = name.value; = city.value;
    data.age = age.value;
    var datas = JSON.stringify(data);
    var ajax = new XMLHttpRequest();"GET","hello.php?data="+datas,false);
    name.value = '';
    city.value = '';
    age.value = '';


b. hello.php

$handle = mysql_connect("localhost","root","indonesia");

$data = $_GET['data'];

// convert the json format to php array style
$data = json_decode($data, true);

$query = "INSERT INTO personal_info (name, city, age) VALUES ";
$query .= "('".$data['name']."', '".$data['city']."', 

$result = mysql_query($query);

No comments:

Post a Comment