whitebear
whitebear

Reputation: 12471

How to get Ajax post request by symfony2 Controller

I send text message like this

html markup

<textarea id="request" cols="20" rows="4"></textarea>

javascript code

var data = {request : $('#request').val()};

$.ajax({
    type: "POST",
    url: "{{ path('acme_member_msgPost') }}",
    data: data,
    success: function (data, dataType) {
        alert(data);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert('Error : ' + errorThrown);
    }
});

symfony2 controller code

$request = $this->container->get('request');
$text = $request->request->get('data');

but $text is null ...

I have tried normal post request (not Ajax) by firefox http request tester.

/app_dev.php/member/msgPost

Controller works and $text has a value.

So I think the php code is OK, there is the problem on Ajax side, however

'success:function' is called as if succeeded.

How can you get the contents of javascript data structure?

Upvotes: 22

Views: 48564

Answers (3)

sf_tristanb
sf_tristanb

Reputation: 8855

First, you don't need to access the container in your controller as it already implements ContainerAware

So basically your code should look like this in your Controller.php

public function ajaxAction(Request $request)
{
    $data = $request->request->get('request');
}

Also, make sure by the data you are sending is not null by using console.log(data) in the JS of your application.

And finally the answer of your question : you are not using the right variable, you need to access the value of $('#request').val() but you stored it in a request variable and you used a data variable name in your controller.

Consider changing the name of the variable, because it's confusing.

Upvotes: 30

mangelsnc
mangelsnc

Reputation: 148

You are doing it wrong when obtaining the value, you must use:

$data = $request->request->get('request');

'cause request is the name of your parameter.

Upvotes: 3

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44851

If you're sending the data as JSON — not as form urlencoded — you need to access the request body directly:

$data = json_decode($request->getContent());

Upvotes: 24

Related Questions