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?
GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
We have seen many times in admin controller when they call ajax request to perform some action, they refer the same admin controller in ajax url instead of different controller, so that they don't need to create any other controller to get response and perform any custom action on that.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With