Saturday, January 19, 2008

JSON, AJAX, & PHP

The last time I did any web programming was about a year ago. Since then a lot has changed in the programming world of web applications. For one, JSON is becoming the new data exchange protocol. Two, PHP has grown drastically. And lastly, there is AJAX - what the web is evolving around - or so I hear.

Recently, I re-entered the world of web programming. After catching up on AJAX and JSON, I decided to put my knowledge of those technologies to work. I began re-writing an earlier project of mine using JSON, AJAX, and PHP. What follows are some pros, cons, tips, and bits of code I think will be useful to the programming community or those just beginning to glance these technologies.

1. Lets talk about JSON

At the moment XML is the preferred data exchange protocol for *serious* web applications. Perhaps XML will remain the preferred protocol for such applications, however, for simpler applications XML is an overkill. What most web applications really need is JSON. There is no doubt in my mind that JSON will become the standard data exchange protocol for simple web applications. Compared to XML, JSON is:
  1. Simpler to learn
  2. Simpler to use
  3. Faster to decode & encode
  4. Smaller in size (the encoded data is smaller)

2. JSON and JavaScript.


There is a bit of confusion about what JSON is in the context of JavaScript. JSON on its own is basically a set of rules for representing data. Those rules however happen to be JavaScript's way of representing objects and arrays. The connection is not accidental - for JSON stands for (
JavaScript Object Notation). However it is important to make the distinction between JSON and JavaScript. JSON in the context of JavaScript is basically a JavaScript object/array, but also JSON is a set of rules, and therefore a language. I find it better to think of JavaScript and JSON as two separate beasts.

Using JSON in JavaScript is fairly easy. Most of the sources on the web show you how to use JavaScript's eval function to decode a JSON string and turn it into a JavaScript object. Though it is a valid way of doing things, I don't like using the eval function, especially when there is a better, secure way. Here is how:

  1. Download json2.js. (Right-click, "Save As")
  2. If you need docs, they are here.
  3. To use json2.js in your html include it via the script tag as you would any other *.js script.

In a nutshell, json2.js has two methods. They are:

  1. JSON.stringify() which takes two parameters, the second being optional
  2. JSON.parse() also takes two parameters, the second being optional

Here is how you use these two methods in JavaScript:


// This is a JavaScript script

// I will use a JavaScript object for this example. You can also use JavaScript arrays, or a
// combination of the two but NOT simple variables such as strings, or integers.
// Keep that in mind as it is the JSON specification/standard.

obj= new Object;
obj["name"]= "John Smith";
obj["email"]= "jsmith@drenintell.com";

// Lets make a JSON string from the JavaScript obj object.

json_string= JSON.stringify(obj);

// Should display: {"name":"John Smith","email":"jsmith@drenintell.com"}

alert(json_string);

// Lets now reverse the process, therefore decoding the JSON string to a JavaScript object.

js_obj= JSON.parse(json_string);

// Lets output the js_obj to see that it is a JavaScript object:

alert(js_obj);

// Lets output one of the object's properties:

alert(js_obj.name);

// End of example.


That's it! How simple was that? Compared to eval, this way of doing things is way easier. First off, using JSON.stringify() means that you will never have to write any JSON strings yourself. Second, using JSON.parse() ensures security, for only JSON strings are parsed and decoded into a JavaScript object/array.


3. JSON and PHP.

Using JSON in PHP is a breeze! It is even easier than using JSON in JavaScript. How ironic! Lets get to it:

PHP5 comes with the JSON libraries already installed and enabled. There is nothing you need to really do. So straight to an example:

// This is PHP script

// A PHP associative array. Keep in mind that in JavaScript an associative array is actually an object.

$obj['name']= 'John Smith';
$obj['email']= 'jsmith@drenintell.com';

// Lets make a JSON string from the associative array.

$json_string= json_encode($obj);

// Should display: {"name":"John Smith","email":"jsmith@drenintell.com"}

echo $json_string;

// Lets now reverse the process, therefore decoding the JSON string to a PHP object.

$php_obj= json_decode($json_string);

// Lets use var_dump() to see all the information about the $php_obj variable.

var_dump($php_obj); // Should be a PHP object.

// Now lets decode the JSON string to a PHP associative array.

$php_assoc_array= json_decode($json_string, true);

// Lets do var_dump() again.

var_dump($php_obj); // Should be a PHP associative array. A handy thing, no doubt!

// End of PHP script

That's it!


4. JSON,
AJAX and PHP. (Perhaps we can call these "JAP")

Unfortunately, AJAX code is long, and takes a great deal of patience to explain. What's also unfortunate is my lack of patience. As a result, you won't see any AJAX here. However, there are several things you should know if you are going to combine
JSON, AJAX, and PHP in a project.

  1. When you make a POST request via AJAX to a PHP script, the POST data is NOT stored in $_POST, but in $HTTP_RAW_POST_DATA.

  2. Using AJAX to submit forms complicates things for you the programmer. For one, you will have to manually get the form field value(s) yourself. But then what? Use JSON to send the form data to PHP.

  3. Forms that submit files cannot be submitted using AJAX. This is not so much a problem with AJAX as it is with browser security. Think about it! If you can send any file via AJAX from a client's computer to a server, then what prevents a hacker from writing a malicious script to send your registry file to his server? Or better yet, your SAM file!

  4. With AJAX you cannot make cross domain requests. There is the "proxy script" solution but that of course means more work for you.

  5. Some web browsers cache AJAX responses. This is often a problem. If a user is seeing the same page when they should be seeing a new page, it's like due to caching. Use PHP's header() function to send the appropriate headers to prevent caching.

  6. If you are going to use JSON, AJAX and PHP, I suggest you make all data exchange happen via JSON. In other words, use JSON for all communication between the server and the client. If you do that, you have to take into consideration the following:
  • How will PHP script errors be displayed? Normally, PHP just outputs the error(s). However, if on the client side you decode all data using JSON, PHP errors won't be displayed as they are not in a JSON format.
  • How will your JavaScript functions know there was a PHP error, even if the error is in a valid JSON format? I suggest you implement a simple error handler on the client side.
  • Exchanging html data using JSON is not recommenced because JSON has to escape all (") and (\) characters, plus several control characters. This happens once on the server, and once on the client. If you have to send large amounts of html using JSON, there will be a performance penalty, as extra processing will take place. Additionally, the size of the data transmitted over the net is larger.
  • Knowing the type of JSON structure your data has is a must. Otherwise, how will you iterate the JSON object(s)/array(s) in JavaScript? Consider reading this tutorial. Also take a look at the following articles:

  • http://ajaxian.com/archives/javascript-associative-arrays-considered-harmful
  • http://www.thedeveloperday.com/iterate-javascript-associative-arrays/
The lesson of this article/post is this:

Do your homework first, as thoroughly as possible, then write code.

JSON is still in its infancy. Exchanging string/text data with JSON isn't a problem, but numeric values might be. There has been several problems reported with JSON's implementation in PHP, however I believe most of them are the result of miss-understanding JSON.


Success is a poor teacher, so if you have any criticism, hopefully constructive, please add a comment.

Regards,
drenintell.

4 comments:

Anonymous said...

json2.js2 uses eval which you can see if you search the file.

nicely written intro tho. thanks.

Anonymous said...

json2.js does use eval, but only so after parsing the JSON string to make sure it is a valid JSON. The author of the script says:

// Parsing happens in three stages. In the first stage, we run the text against
// regular expressions that look for non-JSON patterns. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we want to reject all
// unexpected forms.

Anonymous said...

Thanks for making this so simple to understand.

John Alert said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Online Training from India . or learn thru JavaScript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Online Training