Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Ajax request and response zend framework

I want to send Ajax request to controller, I make like this in the client side

jQuery.ajax({
    url: "public/visits/visit/get-visits",
    type: "POST",
    dataType: 'json',
    data: data,
    success: function(data){
        alert(data)
    },
    error:function(){
        alert("fail :(");
    }
});

at the server side I handle the request as other requests

public function getVisitsAction() {
if (isset($_POST)) {
    $mapper = new Visits_Model_VisitsMapper();
    $allVisits = $mapper->getAllVisits();
    echo json_encode($allVisits);
 }

When I call the action, fail alert occurs and when I check it out through fire bug I found that it returns the json data to client side to page get-visit.phtml.

How can I handle the response in the success function from the page that send the json request and redirecting it to get-visit.phtml page?

like image 838
palAlaa Avatar asked Mar 06 '12 11:03

palAlaa


1 Answers

Zend has Zend_Controller_Action_Helper_Json which do these actions:

$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
echo json_encode($allVisits);
exit;

So it could be even simpler:

public function getVisitsActions() {
    if ($this->getRequest()->isXmlHttpRequest()) {
        if ($this->getRequest()->isPost()) {
            $mapper = new Visits_Model_VisitsMapper();

            $this->_helper->json($mapper->getAllVisits());
        }
    }
    else {
        echo 'Not Ajax';
        // ... Do normal controller logic here (To catch non ajax calls to the script)
    }
}
like image 142
Artur Michalak Avatar answered Oct 12 '22 23:10

Artur Michalak