bodokaiser
bodokaiser

Reputation: 15752

Symfony2 access POST (JSON)

I have a form what jQuery sents for me using Ajax to php.

For this task I use following code:

        $('form').submit(function(event){
        event.preventDefault();
        var form = { message: $('form').serialize() };
        console.log(form);
        $.post('{{ path('PUSChatBundle_add') }}', form, 'json');

This is what firebug sees in the request:

Parametersapplication/x-www-form-urlencoded
message message=Hi+stackoverflowers
Source
message=message%3DHi%2Bstackoverflowers

So and now to Symfony:

public function addAction(Request $request)
{
    $data = json_decode($request->getContent());

    $message = new Message();
    $message->setText($data);

    $em = $this->getDoctrine()->getEntityManager();
    $em->persist($message);
    $em->flush();

    return new Response('Success');
}

For somehow PHP does not manage to decode the json to a PHP-Array.

Regards, B.Kaiser

Upvotes: 0

Views: 4681

Answers (2)

bodokaiser
bodokaiser

Reputation: 15752

I found the source of all evil:

I sent the json threw a php json-validator and I became syntax error.

Strange because jQuery rendered the json var form = $('form').serializeArray();

I now only have to find what in detail is going wrong

Upvotes: 0

xdazz
xdazz

Reputation: 160863

Try $request->getParameter('message');.

Upvotes: 3

Related Questions