<?php
/**
* These 2 functions can be used to pass a PHP array to a javascript function
* via an AJAX callback. See http://www.drlongghost.com/code/json_functions for
* a tutorial on how to use these 2 functions.
*
* @author DrLongGhost
* @version 1.0.0
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
* Constructs a response page in JSON format, based on the $returnArray
* passed to the function. If the json_encode() function exists, as
* with most recent versions of PHP5, then json_encode() is used. If not,
* a simple helper function is used instead. Several lines below which
* are specific to using this function with CakePHP have been commented out.
*
* @return null
* @param object $returnArray
*/
function sendAjaxResponse($returnArray) {
// CakePHP: Disable error messages
//Configure::write('debug', 0);
// Send text/JSON header
header('Content-type: text/plain');
if (function_exists('json_encode')) {
$encoded = json_encode($returnArray);
} else {
$encoded = "{ "; // open JSON object
$returnArrayLength = count($returnArray);
$returnArrayCounter = 1;
foreach ($returnArray as $key => $value) {
$encoded .= "\"$key\"";
$encoded .= ": ";
$encoded .= jsonValue($value);
if ($returnArrayCounter < $returnArrayLength) $encoded .= ", ";
$returnArrayCounter++;
}
$encoded .= " }"; // close JSON object
}
echo $encoded;
return;
// CakePHP: Render the content with the ajax layout
//if($this->layout == 'default') {
// $this->layout = 'ajax';
//}
//$this->set('content_for_layout', $encoded);
//$this->viewPath='/layouts';
//$this->render('ajax');
//return;
}
/**
* This is a helper function to properly quote and escape
* the passed object to convert it into JSON format.
* Handles basic arrays fine, but won't work with nested
* arrays or more complex data.
*
* @return string
* @param object $val
*/
function jsonValue($val) {
if (is_bool($val) || is_numeric($val)) {
return $val; // Return unquoted for bools and numeric
} else if (is_array($val)) {
foreach ($val as $key => $value) {
$val[$key] = str_replace('"','\"',$value); // Escape quotes
$val[$key] = '"'.$val[$key].'"'; // Quote values
}
return '[ '.implode(',',$val).' ]';
} else {
return '"'.str_replace('"','\"',$val).'"'; // Return quoted for strings
}
}
?>