Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

When and why to use Json with PHP

Posted on 2016-10-12
10
Medium Priority
?
107 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
 
LVL 1

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 2000 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
LVL 1

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
 
LVL 1

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 111

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
 
LVL 1

Author Comment

by:Black Sulfur
ID: 41850698
@ Ray,

Noted. Will take that into consideration next time.
1

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

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

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

610 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