GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

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

</div>

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

</script>

b. hello.php
<?php

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

$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']."', 
          ".$data['age'].")";

$result = mysql_query($query);
Share/Bookmark

No comments:

Post a Comment