Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handle JSONP calls in ZEND

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

like image 729
Philipp Kyeck Avatar asked Dec 06 '25 04:12

Philipp Kyeck


2 Answers

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.

like image 114
Charles Avatar answered Dec 08 '25 16:12

Charles


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 ...

like image 25
Philipp Kyeck Avatar answered Dec 08 '25 17:12

Philipp Kyeck