jQuery Parsing PHP JSON Data | Lessoncup Programming Blog

Saturday, 21 December 2013

jQuery Parsing PHP JSON Data

Hi, today i am going to tell you about how to Display the php json data using jquery, a json is a light weight data and easy to write, in php generally we fetch and display the records in our application but sometimes, we use some other Web Services's like Amazon, flicker and other sites to display there data in our websites.


if there is a requirement come to you like write a web Service in that case what you do and how you write a web Service until you don't know about what is web service.. well i will tell you a web Service is URL passed data from other servers and we can access SEND and RECEIVE the data to multiple services VIA web services.

here the concept is simple some other person want's to retrieve the data from your server in that case will you give your server and database details to access him self .. it is nothing but giving a key to someone of your home. in that case you simply write the query and convert the data into a json using json_encode() method and just send that link to him..

JAVASCRIPT

here use $.get() method to access the web services file and use jQuery.praseJSON() or JSON.parse() methods to decode the encoded data which is coming from php file and put it in loop and show the data which place you want..
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>

<script>

$(document).ready(function(){
    
 
 $.get("users.php", function(data) {
  
  var json = jQuery.parseJSON(data);
  
  //else you can use bellow code commented line
  
  //var json = JSON.parse(data);

  for(var i=0;i<json.length;i++){
   
   $("ul").append("<li>"+json[i]+"</li>");
   
  }
  

});

});

</script>

webService

here write the query and convert the object into json at outside of the loop using json_encode() method
<?php
extract($_REQUEST);
include('db.php');

$user=mysql_query("select * from users limit 11");
$obj_user=array();

while($full=mysql_fetch_array($user)){
 
 $obj_user[]=$full['username'];
 
}

echo json_encode($obj_user);

?>


Live Demo   Download Script

No comments :

Post a Comment

Mohammad Khasim
Blogger | Web Developer
Hyderabad - INDIA
lessoncup@gmail.com

PHP | My SQL | JQUERY
Web Development Tools | CMS | Frameworks | SEO

Get my Latest Lessons