Wednesday 19 December 2012

jQuery : Make Ajax Call PHP Script with JSON Return

User experience plays a vital role in excellent web design. AJAX allows you to run server-side validations, form submission, data retrieval, and other server-side stuff in the background (asynchronously) without interfering with the existing page where the request was made. It's a beautiful thing, but best of all it's not very difficult to do.

JSON its self is JavaScript Object Notation and a lightweight data-interchange format.Beside that JSON generate text-based open standard that readable for human. In this time, we'll try using JSON for data transfers and JQuery library for the tool and make AJAX connection.

Assume that we have structure file as below :


So let's move on to the script.

1. html


    JSON JQuery
    
    


    
Nama :
Alamat :
 
Atribut yang sudah terset adalah :
2. getjson.php
$data['nama'] = strtoupper($_POST['nama']);
$data['alamat'] = $_POST['alamat'];

echo json_encode($data);
3. jquery-1.8.3 ( you can download it on : http://jquery.com )

Ok, if we've already make all the file then let's check it in our browser. It's when the button id "setter" didn't clicked :


From the image above we will not see any response from the browser cause the button id setter has not clicked yet. if we fill all the input then we press the setter button, then the browser will display like this :


OK, from the image above you can see there's interaction that happened. The browser make a post request from the background (asynchronously) to getjson.php and then take the response from the file where the data is json formated because from the php file, we use json_encode function.

Note : if you wanna see a response from the background of the browser (here I use firefox) you can install firebug add on to your browser

Done !

Reference :

1. http://en.wikipedia.org/wiki/JSON
2. http://samsonasik.wordpress.com/2010/04/14/jquery-using-json-for-data-transfers/
3. http://www.jonsuh.com/blog/tutorials/jquery-ajax-call-to-php-script-with-json-return/
Copyright © 2012 Clighter | Powered by Blogger