• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 112
  • Last Modified:

When and why to use Json with PHP

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
Black Sulfur
Asked:
Black Sulfur
  • 5
  • 4
1 Solution
 
Evan CutlerVolunteer Chief Information OfficerCommented:
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
 
Black SulfurAuthor Commented:
Thanks Evan,

How could I change the code I posted to use Json?
0
 
Evan CutlerVolunteer Chief Information OfficerCommented:
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Evan CutlerVolunteer Chief Information OfficerCommented:
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
 
Black SulfurAuthor Commented:
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
 
Evan CutlerVolunteer Chief Information OfficerCommented:
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
 
Black SulfurAuthor Commented:
Okay, so in order to better understand it should I learn vanilla javascript or can I learn jQuery?
0
 
Evan CutlerVolunteer Chief Information OfficerCommented:
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
 
Ray PaseurCommented:
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
 
Black SulfurAuthor Commented:
@ Ray,

Noted. Will take that into consideration next time.
1

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

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

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now