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.



The Code

To use this class, just include the class file in your source code:

Adding data to the response:

Indicating there's an error in the request and adding error(s). Notice that by adding error messages, the class will automatically change has_error filed in the response to true:

If you happened to use jQuery, this is how you can process this response:

Pretty neat hut? Here's something more fun. When making server response, you can combine all the steps above into one:

You can assign a key to the error message while adding error message by calling addErrorAssoc method. You can even combine associate and non-associative ones:

For PHP 4 or PHP 5 < 5.2.0

AjaxResult employs native PHP function json_encode. However json_encode hasn't been added until 5.20. So if you are using a PHP which version is lower than that, you need to create this function manually. I included a quick fix for this issue. To emulate this function, include JSONFix.inc.php (provided in the zip file) to your source code.



As always, bug fix, comment, suggestion are welcome.

2 Comments Ajax Response Helper for PHP

  1. mosetsana

    i need a code that i can insert in my website to allow for comments and those comments being shown after submitting as this website does can you pliz help... either send it to my email ad or just post the reply here.

Comments are closed.