How to encode a Javascript function in PHP? I want to encode the callback function with array
$options = array(
'title' => 'Title',
'fnCallback' => someCallback);
equivalent ini Javascript:
var options = {
'title': 'Title',
'fnCallback': someCallback };
I know my PHP code is wrong, how can I fix it?
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
In jQuery you can use the following code to encode the json: var data = {"key1":"value1", "key2":"value2","key3":"value3",...}; $. each(data,function(index,value)){ alert(index+" | "+value); });
php $data = '{ "name": "John Doe", "occupation": "gardener" }'; $a = json_decode($data, true); header('Content-type:text/html;charset=utf-8'); echo "{$a["name"]} is a {$a["occupation"]}"; The example transforms a JSON string into a PHP variable.
The json_encode() function is used to encode a value to JSON format.
Viola i solved my problem with Zend_JSON encoder
$options = array(
'title' => 'Title',
'fnCallback' => new Zend_Json_Expr('someCallback')
);
Zend_Json::encode(
$options,
false,
array('enableJsonExprFinder' => true));
JSON is for passing values around, they are not suitable for passing pieces of code.
You can, instead, pass a function name or other meaningful value and retrieve the right function to call from it on the JavaScript side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With