1

I have problem to return callable function written as php string.

On server side I have:

return = [
    'options' => [
        'timeout' => 3000,
        'callback' => [
            'close' => 'function(){
                alert("Test");
            }'
        ]
    ],
]

In my view model:

<?php echo '<script type="text/javascript">$.jQueryPlugin.defaults = '.json_encode($arrayFromAbove).'</script>';?>

But it does not work since callback is returned as string not callable js function.

Any advise how can I convert string as callable js function?

  • Please, paste the resulting JavaScript code you want to be written on the browser. – NetVicious Mar 21 '17 at 11:24
  • I think is a duplicate of http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string – SrAxi Mar 21 '17 at 11:24

1 Answers1

1

This is what JSON is for i.e. to standardize the data. So, if you have a string in php it will also treated as a string in JavaScript.

So, you need to avoid JSON for it. You just need to echo this separately without JS string quotes. Like:

$.jQueryPlugin.defaults.callback.close = <?php echo $arrayFromAbove['options']['callback']['close']; ?>;

This should work. Or, you can use eval(). But, use of eval is not recommended and is not a good practice to follow. See here.

Community
  • 1
  • 1
Parantap Parashar
  • 1,930
  • 1
  • 14
  • 22