Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 fixed it ? Thanks for advanced.

share|improve this question
    
JSON only allows for values. You cannot reference a function object with it. You can only supply the function name as string, and then handle the resolution in Javascript (using a map or something). –  mario May 29 '11 at 18:43
    
What is someCallback supposed to be? A constant? Because only constants can be references like that. –  Gumbo May 29 '11 at 18:43
1  
I'm guessing that someCallback is a callback function. –  mc10 May 29 '11 at 18:44
    
@Gumbo someCallback is a javascript function. –  brian May 29 '11 at 18:49
    
@mario hmmm there is make sense. Thx mario –  brian May 29 '11 at 18:50
add comment

6 Answers

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.

share|improve this answer
    
alternatively i solve that by returning a string, but this is make the code not "clean" $returnValue = "{'title': 'Title', 'fnCallback': someCallback}"; –  brian May 29 '11 at 18:54
add comment
up vote 4 down vote accepted

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));
share|improve this answer
    
Great to see some actual use of ZF ;-). I went ugly and elegant by adding in the php array 'data'=>'@aCallBack()@' and after json_encode before output, did str_replace('"@','') and ('@"',''). PHP4ever. –  user247245 Dec 7 '13 at 23:47
add comment

To make the notice go away in PHP, just write your callback function in quotes:

$options = array(
   'title' => 'Title',
   'fnCallback' => "someCallback");

And then when you receive the JSON in Javascript, you can remap the callback function name to the actual JS function with e.g.:

json = $.getJSON(..);
json.fnCallback = window[json.fnCallback];   // for global callbacks
share|improve this answer
    
now i know the basic, thank you very much mario –  brian May 29 '11 at 19:03
add comment

You forgot the comma between 'title' and 'fnCallback.'

share|improve this answer
    
oops i'm sorry, but it is not the problem. someCallback is illegal in PHP but not in js. –  brian May 29 '11 at 18:47
    
I know, but you did ask why the PHP code is not working. –  Bryan Dunsmore May 29 '11 at 18:48
    
yeah i supposed JSON_ENCODE can reference the function but i'm wrong see @mario –  brian May 29 '11 at 18:51
add comment

Don't confuse JSON for actual, native, Javascript object notation syntax (regardless of the name). Javascript objects can contain function references; JSON cannot.

share|improve this answer
add comment

That is not possible without thinking of a convention and implementing it yourself.

Say, you have this JSON

'{"title": "Title", "fnCallback": "someCallback" }'

Then you could do, on the client side

function wireupCallbacks(jsonObject) {
  if (typeof jsonObject === "object") {
    for (var prop in jsonObject) {
      var callbackName = jsonObject[prop];
      if (/Callback$/.test(prop) && typeof callbackName === "string") {
        if (typeof this[callbackName] === "function") {
          jsonObject[prop] = this[callbackName];
        }
      }
    }
  }
  return jsonObject;
}

and call that in the context of an object that provides your callback functions

var someObject = {
  someCallback: function() { alert("It works!"); }
}

var jsonObject = {"title": "Title", "fnCallback": "someCallback" };

wireupCallbacks.call(someObject, jsonObject);

jsonObject.fnCallback(); // alerts "It works!"

What's missing:

  • currently the function only looks for properties named "*Callback".
  • there is no fallback to global functions (these would be properties of the window object)
  • there is no recursion (nested objects are not visited)
  • there is no JSON array handling

Add these features on your own, none of these should be difficult to implement.

share|improve this answer
    
yeah beautiful, thanks –  brian May 29 '11 at 19:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.