Solved

When and why to use Json with PHP

Posted on 2016-10-12
10
46 Views
Last Modified: 2016-10-19
I have been trying out some examples of php and ajax in my quest to figure out how to use Ajax. Some examples I have seen use Json to display records from a database and some don't. I just want to understand (in plain english) why you should or shouldn't use Json. This example I found was really easy and it shows all the records from the database but there is not Json involved.

$.ajax({
				
				url:'display_info.php',
				type: 'POST',
				success: function(show_info){
					
					if(!show_info.error){
						
						$('#show-info').html(show_info);
						
						
					}
					
				}
				
			});

Open in new window


display_info.php just has a SELECT query and a while loop.
0
Comment
Question by:Black Sulfur
  • 5
  • 4
10 Comments
 
LVL 9

Expert Comment

by:Evan Cutler
Comment Utility
you don't have to.  you can use XML, a string of delimited data, or a single value.
The idea here is that the response is in some form of format that can be parsed.  In a single AJAX query, you are most likely going to get back as much data as possible in a single request.

Why JSON:
While both are technically strings, JSON compresses better.  Either way, both formats allow for the return of multiple answers in a single response.
In addition, most JQUERY libraries are built to support JSON.  
Not to say you can't parse a XML response, I've done it, but if you grab a JQUERY library with ajax, you might want to run with it to the end.
0
 

Author Comment

by:Black Sulfur
Comment Utility
Thanks Evan,

How could I change the code I posted to use Json?
0
 
LVL 9

Accepted Solution

by:
Evan Cutler earned 500 total points
Comment Utility
two things:

1. change display_info.php.  Make sure that the output of this PHP file is only JSON.
2. Parse the JSON inside the success: block

Here's an example:

Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.

Then you could use the $.each() function to loop through the data:

$.ajax({
    type: 'GET',
    url: 'http://example/functions.php',
    data: { get_param: 'value' },
    dataType: 'json',
    success: function (data) {
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});
or use the $.getJSON method:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});
0
 
LVL 9

Expert Comment

by:Evan Cutler
Comment Utility
for step 1:

<?php
   class Emp {
      public $name = "";
      public $hobbies  = "";
      public $birthdate = "";
   }
      
   $e = new Emp();
   $e->name = "sachin";
   $e->hobbies  = "sports";
   $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
   $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));

   echo json_encode($e);
?>


The above code is an example of PHP generating JSON.  you can use this example to convert your database select statement into a JSON output.
0
 

Author Comment

by:Black Sulfur
Comment Utility
Okay, thank you. Seems more complicated to use Json!

So, is the main benefit that it is faster to use Json? Last question... what am I actually using if I am not using Json? Is it then just jQuery or ajax and is it recommended or better practice to use Json?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 9

Expert Comment

by:Evan Cutler
Comment Utility
remember, you are getting back a string.  nothing more, nothing less.  The string can a single value, or contain multiple values in some form of standard delimited format.  You can even do a comma delimited string (ie.  "value1|value2|value3").  As long as you can parse the information, you are good.

In the case of JSON, they resemble Javascript Objects, in which you can query them efficiently in Javascript.  This might be one of the reasons why most users use them.
0
 

Author Comment

by:Black Sulfur
Comment Utility
Okay, so in order to better understand it should I learn vanilla javascript or can I learn jQuery?
0
 
LVL 9

Expert Comment

by:Evan Cutler
Comment Utility
The right answer: learn javascript so you can understand Jquery.

The Reality answer:  JQuery is javascript libraries.  Jquery is a series of javascript code that was packaged together in usable functions to perform certain actions.  THere are JQuery libraries all over the internet.  IMHO, If you need some javascript in a single perspective, nothing comes close to understanding it (besides formal training ie. videos and website instructions) than Jquery.

However, going to the following sites will give you some good basics:

http://www.w3schools.com/jquery/
http://www.w3schools.com/js/default.asp

They do address the Jquery $.ajax() function there.
1
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Don't know how I missed this one...  Looks like you posted it at 3:10 PM and closed it about an hour later.  For E-E, which has a world-wide audience, it's usually a good idea to leave any question open for at least 24 hours.

Here's an article you might find useful:
https://www.experts-exchange.com/articles/22519/Understanding-JSON-in-PHP-and-JavaScript-Applications.html

You also want to get the latest edition of this book:
https://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527

And this one, too.  You won't need any other JavaScript books.
https://www.amazon.com/gp/product/0596517742/
1
 

Author Comment

by:Black Sulfur
Comment Utility
@ Ray,

Noted. Will take that into consideration next time.
1

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now