How can I get JSON in symfony2

I am currently working on a symfony2 based project with a lot of ajax use.

Now I want to send JSON via $.ajax();(type POST) and process it in the symfony2 controller. But I'm not quite sure how I access JSON inside the controller.

Now I have the following:

JS:

            $.ajax({
                url: url,
                type:"POST",
                data:json,
                success:function (data) {
                    $('div.tooltip p').html(data);
                }
            });

And PHP:

    public function registrationAction(Request $request) {
        if($request->getMethod() == 'POST') {
            // How to receive??
        }

        return $this->render('KnowHowERegistrationBackendBundle:Create:registration.html.twig');
}

The only thing I don't know is how can I access JSON? I am sure that it is quite easy, I just do not see it. Thank you for your help!

+5
source share
2 answers

your code, I think, is not complete, if you want to send data to a server with json format, I think setup $ .ajax like this, just an example

$.ajax({
                url: url,
                type:"POST",
                data:"JSONFile=" + json,
                success:function (data) {
                    $('div.tooltip p').html(data);
                }
            });

JSONFile , json- json .

php:

$json = $_POST['JSONFile'];

var_dump(json_decode($json));
var_dump(json_decode($json, true)); //true option if you will convert to array

symfony2 direct acces $_POST , $request = $this->getRequest(); $request->request->get('JSONFile'); // get a $_POST parameter

+3

ajax u /json:

$.ajax({
      url: url,
      type:"POST",
      contentType: 'application/json',
      data:json,
      success:function (data) {
           $('div.tooltip p').html(data);
      }
});

:

if($request->getMethod() == 'POST') {
    if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
        $data = json_decode($request->getContent(), true);
        $request->replace(is_array($data) ? $data : array());
    }
}

Silex http://silex.sensiolabs.org/doc/cookbook/json_request_body.html

+13

All Articles