Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Ajax post request by symfony2 Controller

Tags:

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?

like image 390
whitebear Avatar asked Sep 16 '13 11:09

whitebear


People also ask

Is AJAX request GET or POST?

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.

Do AJAX requests require their own separate controller actions?

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.


2 Answers

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.

like image 96
sf_tristanb Avatar answered Oct 22 '22 16:10

sf_tristanb


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()); 
like image 41
Elnur Abdurrakhimov Avatar answered Oct 22 '22 16:10

Elnur Abdurrakhimov