PHP, JSON and JavaScript usage

Written by on July 17, 2008 in Ajax, PHP - 50 Comments

Today i want to introduce you to jSON (JavaScript Object Notation), in short, it is a simple format designed to exchange data between different programming languages. I will show you how to create JavaScript object, convert it to JSON string, and send to PHP script, which will decode jSON string to readable format (for PHP). But that’s not all, PHP script will create it’s own data object encode it to jSON string and send it back. All communication between JavaScript and PHP will be done thru AJAX.

If you haven’t heared about jSON yet, then you can visit Wikipedia for more information. The other technology you need to be familiar with before reading this article is AJAX. If you need to, you can read my Introduction to AJAX post.

JSON objects

Usually when it comes to JSON we have an encoded string in mind, however JSON is a subset of JavaScript and in this programming language it can be used as is, to create objects. Simple JavaScript object created using JSON notation can look like this:

var JSONstring = 
{
    "firstname": "Greg", 
    "email": "greg@fake_email.com",
    "hobby": 
    [
	{
	    "hobbyName": "sport", 
            "isHobby": "true"
	},
        {
		"hobbyName": "reading", 
	        "isHobby": "true"
	},
        {
		"hobbyName": "music", 
	        "isHobby": "false"
	}
    ]
};

Accessing fields is done like in any other JS object (mainly because it is “normal” JavaScript object), if we want to know if hobby “reading” was checked then we would have to write:

JSONstring.hobby[1].isHobby; // true

Creating JavaScript Objects

Before we start, we will need something to work with. We will create HTML form with “validate” button, when someone clicks this button the whole proccess i described in the first paragraph will start. Also, despite JSON is a subset of JavaScript there are no built in function for converting JavaScript object into JSON string, so we will use already created class available at JSON homepage, the file is located here json2.js.

Here is the code for the HTML form, i think there is no need to explain it:

</script>
<html>
<head><TITLE>ditio.net jSon Tutorial</TITLE>
<script src="http://www.json.org/json2.js"></script>
<script>
// JavaScript source code will be here
</head>
<body>
<form name="personal" action="" method="POST">
Name <input type="text" name="firstname"><br>
Email <input type="text" name="email"><br>
Hobby 
	<input type="checkbox" name="hobby" value="sport"> Sport
	<input type="checkbox" name="hobby" value="reading"> Reading
	<input type="checkbox" name="hobby" value="music"> Music
<input type="button" name="valid" value="Validate" onclick="validate()">
</form>
</body>
</html>

After clicking “validate” button validate() function will be called, we need to add it, in head section for example:

function validate()
{
    var p = document.forms['personal'];
 
    var JSONObject = new Object;
    JSONObject.firstname = p['firstname'].value;
    JSONObject.email = p['email'].value;
    JSONObject.hobby = new Array;
 
    for(var i=0; i<3; i++)
    {
        JSONObject.hobby[i] = new Object;
	JSONObject.hobby[i].hobbyName = p['hobby'][i].value;
	JSONObject.hobby[i].isHobby = p['hobby'][i].checked;
    }
 
    JSONstring = JSON.stringify(JSONObject);
    runAjax(JSONstring);
 
}

Code is quite easy to understand. First i assign whole form to variable p just to make further access to this form data easier. In next lines JavaScript object is created, as you can see it consists only from Object and Array data objects.

Note that this is completely the same object as in first listing of this tutorial, however different method was used to create it.

Sending JSON object to PHP with AJAX

I do not want ot get into AJAX here because it is not the topic of this tutorial, i will use code from my Introduction to AJAX post, if you do not want ot go there then remember that at the end of this article there is whole source code waiting to be downloaded.

var request;
function runAjax(JSONstring)
{
    // function returns "AJAX" object, depending on web browser
    // this is not native JS function!
    request = getHTTPObject();
    request.onreadystatechange = sendData;
    request.open("GET", "parser.php?json="+JSONstring, true);
    request.send(null);
}
 
// function is executed when var request state changes
function sendData()
{
    // if request object received response
    if(request.readyState == 4)
    {
	// parser.php response
	var JSONtext = request.responseText;
	// convert received string to JavaScript object
	var JSONobject = JSON.parse(JSONtext);
 
	// notice how variables are used
	var msg = "Number of errors: "+JSONobject.errorsNum+
		"\n- "+JSONobject.error[0]+
		"\n- "+JSONobject.error[1];
 
	alert(msg);
    }
}

That’s it we are half way there, now we need to create PHP script to handle AJAX request.

JSON and PHP

Decoding JSON string is very simple with PHP only one line of code is needed to parse string into object. Similary only one function is needed to encode PHP object or array into JSON string, look at the code:

<?php
 
// decode JSON string to PHP object
$decoded = json_decode($_GET['json']);
 
// do something with data here
 
// create response object
$json = array();
$json['errorsNum'] = 2;
$json['error'] = array();
$json['error'][] = 'Wrong email!';
$json['error'][] = 'Wrong hobby!';
 
// encode array $json to JSON string
$encoded = json_encode($json);
 
// send response back to index.html
// and end script execution
die($encoded);
 
?>

It is also interesting what is inside $decode variable

stdClass Object
(
    [firstname] => fgfg
    [email] => 
    [hobby] => Array
        (
            [0] => stdClass Object
                (
                    [hobbyName] => sport
                    [isHobby] => 1
                )
 
            [1] => stdClass Object
                (
                    [hobbyName] => reading
                    [isHobby] => 
                )
 
            [2] => stdClass Object
                (
                    [hobbyName] => music
                    [isHobby] => 
                )
 
        )
)

PHP finished execution, then “request” object status in JavaScript is now equal to 4. Response text (in sendData() function) will be parsed with JSON class to object and used to display message on the screen. Note that instead of using JSON.parse() we could use JavaScriipt eval() function.

Conclusion

This tutorial was intended to introduce you to JSON, and i wanted to make this tutorial as clear as possible so i intentionally used the simplest methods to achieve my goal. However this tutorial wouldn’t be complete if i wouldn’t give you further resources from which you can learn more.

First you should check out is Zend_Json class (a part of Zend Framework), it has the same functionality as json_decode() and json_decode(), but can handle more complicated JSON strings then those two functions.

Second is json.org home of JSON, check especially this tutorial, it has got great examples of more advanced JSON class usage.

About the Author

Greg Winiarski is a freelance PHP and JavaScript programmer. He specializes in web applications and WordPress development.

50 Comments on "PHP, JSON and JavaScript usage"

  1. bbb July 19, 2008 at 5:39 pm ·

    That was easy to follow through.
    Thanks!

  2. chris August 2, 2008 at 4:36 am ·

    Nice tutorial. I do have one question though. I tried processing the JSON (as passed from my php remote script) in a javascript function, but it hasn’t worked. The js function treats the returned value as text instead of a json object. Any ideas?

    function helloCallback(data,ioArgs) {
    var obj = data; // where data is a json_encode() string from php
    }

  3. Greg August 2, 2008 at 7:53 am ·

    Hi Chris thanks for your comment.

    Actually you are receiving string and that is OK, now you need to parse it to JavaScript object:
    var JSONobject = JSON.parse(data);
    or
    var JSONobject = eval(data);

    second example will work always, the first one only if you are using json2.js

    Hope that helps.

  4. Charles October 18, 2008 at 9:02 am ·

    Hiii….. This tutorial is awesome and it will be useful for many people. Everything is fantastic here but please keep the bookmarking button here so that it can promote your site at the same time many will bookmark ( including me :)

  5. Greg October 19, 2008 at 7:11 am ·

    Hi Charles, i was using bookmarking buttons, but no one seemed to be interested in clicking them so eventually i decided to remove them as they were just wasting space.

    However maybe i will consider placing here one button that will allow to bookmark pages.

  6. Mandy November 29, 2008 at 1:59 am ·

    Thanks, very handy. I’m using JSON now with the jQuery form plugin:

    http://malsup.com/jquery/form/#code-samples

    Cheers,

    Mandy

  7. sanjay March 17, 2009 at 2:49 pm ·

    Hi.. I am new to Json.. I am trying to use your code but getting error saying JSON is not defined. I have included the json2.js but still getting the eroror. Do i need to do something explicitly.

  8. Greg March 17, 2009 at 8:36 pm ·

    No, it should work fine as is. Maybe try using the code i attached at the end of the post. Unzip it and run, if it will work, you can probably take it from there. This is how i do it … step by step :) good luck sanjay.

  9. sanjay March 22, 2009 at 7:08 pm ·

    Hi Greg. Thanks for your reply. Yeah i guess i was doing some mistake by myself. It is working fine. I am able to hook the thing into my project now. Thanks a lot. It fits most suitably in my product. Thanks again.

  10. sanjay March 25, 2009 at 11:06 am ·

    I have one more doubt. In this case i have to call a separate script each time i want to perform some action. E.g. – for saving i will have to call a save script for delete i will have to call a delete script.

    What i want is to have one file with all functions and call a particular function in some file.
    One way i can think of is passing the function name in the parameter. But is there any better way which i can use???

    Thanks in advance.

  11. Luci April 9, 2009 at 8:21 am ·

    Thanks for this tutorial :)

  12. satish April 18, 2009 at 11:53 am ·

    I have array ordertext i want to assign the array value
    as below
    JSONObject.ordertext[i] but it not coming its saying ordertext[i] is undefined

  13. ronggur April 24, 2009 at 7:49 am ·

    hi Greg, thank’s a alot for the tutorial..

    just wanna add some small thing in the php file..

    somehow in my php code, it won’t parse the ‘$decoded = json_decode($_GET['json']);’ part.. until i added stripslashes function to $_GET['json'].

  14. Greg April 24, 2009 at 4:41 pm ·

    Hi Ronggur and thanks for the useful commnet.

    I think it is because you had “magic_quotes_gpc” set to on in your php.ini file.

  15. Nora May 16, 2009 at 4:23 pm ·

    If you had some way of rating posts I would for sure give you a high rating my friend!

  16. Manas June 23, 2009 at 6:10 pm ·

    Hey that was awesome!!!..exactly what I was looking for

  17. Sajjan June 27, 2009 at 3:08 am ·

    Hi,

    I am using json2.js and trying to parse array but I am getting a script error saying “text.replace is not a function” json2.js(line 452)

    Here is the variable that i am trying to parse:

    var menuData =
    {
    menus:[
    {
    id:'17',
    text:'menu1',
    items:['aaa','bbb']
    },
    {
    id:'19',
    text:'menu2',
    items:['ccc','ddd']
    },
    {
    id:'18',
    text:'menu3',
    items:['eee','fff']
    }
    ]
    };
    menuData = JSON.parse(menuData);

  18. Mary July 3, 2009 at 9:54 pm ·

    Thoughtful post and well written. Please write more on this if you have time.

  19. Ahmad Ginani August 23, 2009 at 2:30 pm ·

    Thanks for your tutorial, It is very useful for me.

  20. jconstantino August 27, 2009 at 1:16 pm ·

    Thank you!

  21. PaulBM August 31, 2009 at 1:56 am ·

    Superb tutorial. I’ve improved my JSON knowledge greatly thanks to your work. I was stuck at first until I read ronggur’s comment about stripslashes().

  22. jaywink September 5, 2009 at 4:35 pm ·

    Thanks! This was a great help getting to learn something about JSON

  23. manki December 2, 2009 at 2:12 am ·

    Hey thanks a lot! that was exactly what I’ve been looking for.
    great job!

  24. Alex December 26, 2009 at 6:49 am ·

    So how do you use the decoded variable in your PHp file?

  25. v14nt0 January 19, 2010 at 4:28 am ·

    Great tutorial…,
    How about the opposite of this, like
    PHP->JSON->javascript

    -PHP : Get server side data or query
    -JSON:convert it to JSON
    -javascript: use the data with javascript

    THanks,

  26. Edgar Catalán March 17, 2010 at 12:13 am ·

    v14nt0, you can try this:

    -PHP: use json_encode($YourDataArray).
    -JavaScript: Here I use evalJSON() function from Prototype Framework, which converts a string into a javascript Object so you can work with your data.

    Some references:
    http://www.prototypejs.org/api/string/evalJSON
    http://www.prototypejs.org/learn/json

    Note: json_encode() and json_decode(), are only available from PHP 5.2, if you have 5.1.x (as I do) you can try this workaround:

    http://www.boutell.com/scripts/jsonwrapper.html

  27. mike April 18, 2010 at 9:06 pm ·

    did u mean?

    like i said, im nubie, sigh*

    /*

    // JavaScript source code will be here
    //<<<<this is missing in your code

    */

  28. amishera May 15, 2010 at 9:56 pm ·

    with this code:

    why am I getting?

    Notice: Undefined index: json in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\JSONExample.php on line 2

  29. Denis Maybir May 17, 2010 at 8:10 am ·

    Thanks, very helpful!!! :D

  30. Ronald May 18, 2010 at 12:38 am ·

    Hi, question! how will you put this into your php array? http://api.freelancer.com/Project/Search.json?keyword=iphone&count=1&order=rand

    or rather.. how will you create an output with a table?

  31. Greg Winiarski May 18, 2010 at 5:37 pm ·

    @Roland why put it in the tables? Just json_decode it and use as an object.

  32. bugoy July 28, 2010 at 8:35 am ·

    Great article!!!

  33. Vinothkumar Arputharaj July 29, 2010 at 9:53 am ·

    Hi,

    I tried this example in my localhost. The code in the javascript file below “Sending JSON object to PHP with AJAX” is not compiling after the line:24

    var JSONobject = JSON.parse(JSONtext);

    Therefore, I have used stringify,

    var JSONobject = JSON.stringify(JSONtext);

    and the code gets compiled and I am able to get the JSONobject. But,

    JSONobject.errorsNum

    is returning as ‘undefined’

    Please help me in this.

    Alert me at “vinothkumar_a@hcl.in”

    Thank you.

  34. Vinothkumar Arputharaj July 29, 2010 at 10:01 am ·

    In the above issue, line:24

    var JSONobject = JSON.parse(JSONtext);

    returns an undefined error while subject to try{}catch{}

  35. plokko August 7, 2010 at 9:23 pm ·

    Remember to quote the & characters when sending data with ajax with get or post,each variable is divided with the & so i had problem in the past figuring out why he was cutting my variables,i fixxed it replacing & with #E and #E with ##E in js and the backworse in php.

  36. admire August 31, 2010 at 8:53 am ·

    Great articles thanks !!!!!!!!!!1

  37. Houston Car Insurane October 11, 2010 at 2:53 am ·

    Great Web site! I was wondering if I could quote a portion of your pages and use a handful of items for a term paper. Please email me whether that would be fine. Thanks

  38. maneki November 6, 2010 at 3:42 pm ·

    Yees! thank you, that what I was looking for :)
    BTW, Great website.

  39. deepch November 26, 2010 at 12:10 pm ·

    Very nice and helpful tutorial…for beginners
    with this tutorial i learn what is JSON in real.

  40. diamondsea February 23, 2011 at 9:20 pm ·

    DON’T use eval(), use JSON.parse() instead.

    Using eval() will allow the remote server to execute ANY javascript code on your browser.

    This creates a huge security vulnerability for anyone who can hack or intercept the communications between the browser and the server.

    JSON.parse() will return an object with the values that you can extract out as needed, without running arbitrary code in your browser.

  41. jfbcb March 2, 2011 at 4:43 am ·

    very good! well,i also want to know if i use return data ,how can i use the data by use javascript.poor enligh,thank u so much.

  42. jai March 9, 2011 at 7:57 am ·

    Hi guys
    I got this error after execution. Can anybody help?
    getHTTPObject is not defined

  43. Tennek March 10, 2011 at 7:32 pm ·

    Where is the whole code attachment? Can’t find it :s

  44. Søren April 1, 2011 at 11:24 am ·

    JSON is NOT a subset of Java Script. A common mistake made by amatures.
    However this was a pretty good guide but would like some more DECODING from Httprequest results. :-)

  45. Code April 6, 2011 at 1:21 pm ·

    Hmm, is there a link somewhere to download the code?

  46. RT April 15, 2011 at 9:48 am ·

    Looks like is down. I got a copy off of github, but nowhere do I see the getHTTPObject function. Help!

  47. Bart April 20, 2011 at 3:01 pm ·

    Jai – look at http://ditio.net/2007/07/14/your-very-first-ajax-web-application/

    it is linked as intro to ajax. GettHTTPObject function is there. Copy and paste works.

  48. rajwinder July 24, 2011 at 10:23 am ·

    I am completely new to json. so thanx for such a tutorial.hope i will use it efficiently.

  49. ManojKumar B August 18, 2011 at 5:15 pm ·

    Thanks Greg Winiarski for this nice tutorial. This helped me relieve from the stuck of coding. And i learned a new thing.
    Thanks again. Keep rocking…

  50. John October 4, 2011 at 3:44 pm ·

    This was a great tutorial and I really benefitted from it.
    I am stuck on a problem of sending html inside json encoded string.

    I have an array that contains html link markup.

    for example,
    $lnk = ‘Link‘;
    $a = array($lnk);

    When I useo php json_encode it converts this string to the following format.

    ["Link 1 "]

    Now how can I get the original markup from this json encoded string?
    I tried decodeURI and it does not work as intended in Chrome but works in FF.

    Please let me know if you have any ideas about this issue.

Leave a Comment