2

couldn't find an answer via search (or google) so i'll ask it myself. is it possible to handle JSONP calls to the zend framework?

only found this page:

http://framework.zend.com/wiki/display/ZFPROP/Zend_Json_Server+-+Lode+Blomme

but i'm not sure if it is already implemented!?

thx

Vika
  • 3,275
  • 18
  • 16
Philipp Kyeck
  • 18,402
  • 15
  • 86
  • 123

2 Answers2

9

JSONP is just a JSON response that is wrapped in a specified callback function that is executed on the client.

Zend_Json_Server is only for JSON-RPC at the moment. The link you found is an archived (unimplemented) proposal to add JSONP support.

The good news is that you don't need any sort of framework to support JSONP. Assuming $response is the data you wish to return to the user, and $callback contains the sanitized callback:

echo $callback, '(', json_encode($response), ');';

Tada, you've JSONP'd.

Please take care to read the document I linked about sanitizing the callback. Failure to sanitize the callback may result in an exploitable condition.

aporat
  • 5,922
  • 5
  • 32
  • 54
Charles
  • 50,943
  • 13
  • 104
  • 142
  • hi charles. thanks for the quick reply. i know that i don't have to use any framework, but what if i already am ... :) will read the document about sanitizing and try to implement it using the zend framework. and will post if it worked. thx – Philipp Kyeck Mar 21 '11 at 19:13
  • finally had the time to check up on this - and it really works great. thanks. – Philipp Kyeck Mar 25 '11 at 15:00
2

for those of you that are using ZEND framework and want to know what i had to change in order to get this working ...

had to make changes on a couple of files:

1) added a new layout under VIEWS > LAYOUTS called json.phtml

<?php  
    header('Content-type: application/javascript');  
    echo $this->layout()->content;  
?>

2) controller

added a new action called jsonAction

public function jsonAction()  
{
    $this->_helper->layout->setLayout('json');  

    $callback = $this->getRequest()->getParam('callback');
    if ($callback != "")
    {
        // strip all non alphanumeric elements from callback
        $callback = preg_replace('/[^a-zA-Z0-9_]/', '', $callback);
    }  
    $this->view->callback = $callback;  

    // ...  
}

3) added a new view under VIEWS > SCRIPTS > json.phtml

<?php  
if ($this->callback != "")  
{  
    echo $this->callback, '(', json_encode($response), ');';   
}  
else  
{  
    echo json_encode($response);  
}
?>

now i can make an ajax call via jquery like this:

$.ajax({
    type: "GET",
    url: 'http://<your_url>/<your_controller>/json',
    data: {},
    dataType: "jsonp",
    success: function(json) {
        console.log("success");
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("error("+jqXHR+", "+textStatus+", "+errorThrown+")");
    }
});

maybe this helps someone ...

Philipp Kyeck
  • 18,402
  • 15
  • 86
  • 123