22

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?

1
  • 1
    Try this one in your controller $text = $this->getRequest()->get('request'); Commented Sep 16, 2013 at 12:06

3 Answers 3

30

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.

Sign up to request clarification or add additional context in comments.

Comments

24

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());

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.