Ajax Response Helper for PHP

In Ajax programming development, passing data back and forth between client and server is a common task. There are two major data formats that one can use for this purpose, namely XML and JSON. My personal preference is JSON because I find it's less verbose and easier to parse.

Although latest PHP provides a very handy function (json_encode) for outputting data in JSON format, for almost every Ajax request I handle on the server side, I have to routinely format the data in a certain way so I can use it conveniently on the client side. For example, to indicate whether it is a valid Ajax request, I embed an field called has_error in every response. I find it's getting annoying after a while, so I wrote a class to automate things a bit.

Continue reading

Easy JSON Encoding/Decoding in PHP

Update(2009-09-19): JSON encoding and decoding is built into PHP since PHP 5.20. You don't need Zend's JSON support if your PHP version is >= 5.20. Please see:

http://us2.php.net/manual/en/function.json-encode.php



http://us2.php.net/manual/en/function.json-encode.php

So you are writing a piece of PHP code to handle some Ajax request and you've just finished coding the business logic. It is time to output some server response so that the page which initiated the Ajax request can obtain the requested result.

You decided to use JSON because you don't want to get your hands dirty by traversing nodes after nodes. After encoding a fairly complex and nested PHP array into JSON, you find out writing such code is very unpleasant and you start wondering if there is an easier way to do this. The answer is yes - Zend Framework will save your day.

Continue reading