Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend and Jquery (Ajax Post)

I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.

//submit.js

$(function() {

    $('#buttonSaveDetails').click(function (){
        var details = $('textarea#details').val();
        var id = $('#task_id').val();
        $.ajax({
            type: 'POST',
            url: 'http://localhost/myproject/public/module/save',
            async: false,
            data: 'id=' + id + '&details=' + details,
            success: function(responseText) {
                //alert(responseText)
                console.log(responseText);
            }

        });
    });
});

On my controller, I just don't know how to retrieve the POST data from ajax.

public function saveAction() 
{

    $data = $this->_request->getPost();
    echo $id = $data['id'];
    echo $details = $data['details'];
    //this wont work;
}

Thanks in advance.

like image 812
jaym Avatar asked Dec 30 '10 03:12

jaym


2 Answers

Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:

$('#buttonSaveDetails').click(function (){
    var details = $('textarea#details').val();
    var id = $('#task_id').val();
    $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'http://localhost/myproject/public/module/save',
            async: false,

            // you can use an object here
            data: { id: id, details: details },
            success: function(json) {
                console.log(json.id + ' ' + json.details);
            }
    });

    // you might need to do this, to prevent anchors from following
    // or form controls from submitting
    return false;
});

And from your controller, send the data like this:

$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));

As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.

like image 126
karim79 Avatar answered Oct 08 '22 19:10

karim79


Simplest way for getting this is:

$details=$this->getRequest()->getPost('details');

$id= $this->getRequest()->getPost('id');

Hope this will work for you.

like image 32
2 revs, 2 users 57% Avatar answered Oct 08 '22 17:10

2 revs, 2 users 57%