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:
include 'AjaxResult.class.php';
$r = new AjaxResult();
echo $r;
//JSON output
{"has_error":false,"result":[]}
Adding data to the response:
include 'AjaxResult.class.php';
$r = new AjaxResult();
$data = array(
'data1'=>5,
'data2'=>10
);
$r->setResult($data);
echo $r;
//JSON output
{"has_error":false,"result":{"data1":5,"data2":10}}
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:
include 'AjaxResult.class.php';
$r = new AjaxResult();
$r->addError('Something is wrong');
echo $r;
//JSON output, has_error changed to true
{"has_error":true,"errors":["Something is wrong"],"result":[]}
If you happened to use jQuery, this is how you can process this response:
<script type="text/javascript">
$.get('example.php', {}, function(data){
if(data.has_error){
alert(data.errors[0]);
return;
}
//do stuff as usual
var result = data.result;
...
}, 'json');
</script>

Pretty neat hut? Here's something more fun. When making server response, you can combine all the steps above into one:
include 'AjaxResult.class.php';
//Another way of creating AjaxResult instance:
AjaxResult::create()
->setResult(array('a'=>'aa')) //this one is optional
->addError('a is not aa')
->toJSON(true); //true means output insteand of returning the string
//JSON output
{"has_error":true,"errors":["a is not aa"],"result":{"a":"aa"}}
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:
include 'AjaxResult.class.php';
AjaxResult::create()
->addError('a is not aa')
->addErrorAssoc('message', 'this is an error message')
->toJSON(true);
//JSON output
{"has_error":true,"errors":{"0":"a is not aa","message":"this is an error message"},"result":[]}
//In JavaScript (assuming you are using the jQuery example a few sections above):
alert(data.errors[0]);
alert(data.errors.message);
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.
Conclusion
As always, bug fix, comment, suggestion are welcome.
More interesting posts ...
Leave a Comment
If you would like to make a comment, please fill out the form below.
If you want to post source code, please wrap it with <pre> and </pre>

