Solved

When and why to use Json with PHP

Posted on 2016-10-12
10
71 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
ID: 41840869
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
ID: 41840885
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
ID: 41840889
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
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 
LVL 9

Expert Comment

by:Evan Cutler
ID: 41840893
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
ID: 41840912
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
 
LVL 9

Expert Comment

by:Evan Cutler
ID: 41840924
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
ID: 41840936
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
ID: 41840947
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 109

Expert Comment

by:Ray Paseur
ID: 41850680
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
ID: 41850698
@ Ray,

Noted. Will take that into consideration next time.
1

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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, …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

838 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