rii
rii

Reputation: 57

zf2 get the JSON value in the controller

I'd like to know how i can get the json value in the zf2 controller.

My json function:

$(".bajaAlumno").click(function () {
    var dat =$(this).attr('id');
    var response = '{"name":"' + dat + '"}';
    alert(response);
    $.ajax({
        url: 'bajaAlumnos',
        dataType: 'json',
        data: JSON.stringify(response),
        type: 'post',
        contentType: 'application/json',

        success: function (data) {
            alert(data);
        },

        error: function (jqXHR, textStatus, errorThrown) {
            console.log("Error... " + textStatus + "        " + errorThrown);
        }
    });
})

And i try this:

//module.config.php
'strategies' => array(
    'ViewJsonStrategy',
),

And in the controller:

public function bajaAlumnosAction()
{
     $request = $this->getRequest();
     die(var_dump($request->isPost()));
     //this is equals FALSE
}

What i do wrong?

add in i tries this

die(var_dump($this->getRequest()->getContent());
die(var_dump(var_dump($request->getPost()->toArray())));

and the same result array(0) , please help

Upvotes: 1

Views: 3903

Answers (3)

akond
akond

Reputation: 16035

$values = \Zend\Json\Json::decode ($this->getRequest ()->getContent ());

Upvotes: 1

Mohammad Mehdi Habibi
Mohammad Mehdi Habibi

Reputation: 1623

See this tutorial: Returning JSON from a ZF2 controller action

And try this in your controller:

use Zend\View\Model\JsonModel
public function bajaAlumnosAction()
{
     $request = $this->getRequest();
     $result = new JsonModel($request->getPost()->toArray());
     return $result;
}

Upvotes: 1

kilop
kilop

Reputation: 383

use $request->isXmlHttpRequest() in your controller when using Ajax.

Upvotes: 0

Related Questions