1

I need to pass json data to my Symfony Controller. My ajax function looks like this:

var data = '{"firstname":"John"}';
$.ajax({ 
type: "POST", 
url: save_url, //path to controller action 
data: {json:data},
success: function(response) {
 // Do something 
}
}); 

In my controller, I try to get my data through:

public function createAction(Request $request) {
 $data = $this->getRequest()->get('firstname'); 
 return $this->render('MyBundle:Counter:test.html.twig', array(
 'data' => $data 
 )); 

Just to see if this works, I send $data to be echoed in a template. In Firebug I can see the data being sent and everything seems to work, but $data is empty and nothing is echoed. Where am I doing this wrong?

EDIT: When I check the response in Fireburg console, I see my data there, in place, but it never appears in the template. var_dump($data) tells that $data is null. So, it seems data is being sent but the controller ignores it.

Dhia Djobbi
1,2922 gold badges21 silver badges38 bronze badges
asked Oct 7, 2013 at 13:50
1
  • 1
    Shouldn't it be just $request->get('json'); ? Commented Oct 7, 2013 at 13:58

4 Answers 4

1

As Marek noticed:

$this->getRequest()

already returns the request object, you're accessing the request property of the request, that doesn't add up. Either try:

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

Or use:

$data = $this->getRequest()->get('json');

You can, of course assign the return value of $this->getRequest() to a variable, and call the get method on that var from there on end... anyway, here's my initial answer, it does contain some more tips, and considerations you may find useful:

You should be able to get the data this way, though AJAX requests + echoing in a template? That does sound a bit strange. I don't see you passing the $data variable to a $this->render call anywhere.

This is a copy-paste bit from a controller action in one of my projects. It works just fine there:

public function indexAction()
{
 if (!$this->getRequest()->isXmlHttpRequest())
 {//check if request is AJAX request, if not redirect
 return $this->redirect(
 $this->generateUrl('foo_bar_homepage')//changed this, of course
 );
 }
 $id = $this->getRequest()->get('id',false);//works fine

However, I can't begin to grasp why you're doing this:

 var data = '{"firstname":"John"}';

Why not simply go for:

$.ajax({
 type: "POST",
 url: url,//post how you get this URL please...
 data: {firstname: 'John'},//jQ will sort this out for you
 success: function(response)
 {
 console.log(response);
 }
 error: function()
 {
 console.log('an error occured');
 console.log(arguments);//get debugging!
 }
});

Then, in your controller you're able to:

$this->getRequest()->get('firstname');//it should be John

You could even pass {json:{firstname: 'john'}} as the data param to $.ajax, the only difference in your controller will be, that you have to do this:

$data = $this->getRequest()->get('json');
$firstName = $data['firstname'];

That should work just fine, unless there's somthing you're not telling us :)

RECAP:
This is what I'd write:

public function createAction()
{//no Request param in controller
 if (!$this->getRequest()->isXmlHttpRequest())
 {//no ajax request, no play...
 $this->redirect(
 $this->generateUrl('homepage_route')
 );
 }
 $data = $this->getRequest()->get('firstname');
 //return json response:
 return new Response(json_encode(array('dataReceived' => $data));
 //return rendered HTML page:
 return $this->render('MyBundle:Counter:test.html.twig', array(
 'data' => $data 
 ));
}

Of course, then the JS code should read:

$.ajax({ 
 type: "POST", 
 url: 'route/to/create'
 data: {firstname:'John'},
 success: function(response)
 {
 console.log(response);
 }
});

I have tested this, and I see no reason why this shouldn't work. It works just fine for me...

Yang
8,7308 gold badges35 silver badges61 bronze badges
answered Oct 7, 2013 at 14:00
10
  • I´ve tried everything in your examples, but the result is still empty. I updated my question. Commented Oct 7, 2013 at 19:34
  • @tofu: You're not showing us how you're getting the data. jQ also has well documented default behaviour: $.ajax sends the data as x-www-form-urlencoded mime-type, so you needn't decode it. Even if you were to send the data as JSON, I do believe Symfony decodes it for you. Please add the code you're using to decode to your question, so we can verify that Commented Oct 8, 2013 at 6:32
  • But the main problem still is the request result is empty. I´m not decoding yet, I only thought that I might need to do that. The first step is to make sure that I CAN send data to my controller. Commented Oct 8, 2013 at 8:01
  • @tofu: of course, but if you don't show us how you're trying to get the data into your controller (how you're assigning to $data), we can't say for sure there's no mistake being made there, can we? you've just pasted $data = //get json and decode, which doesn't show how you're assiging anything to $data. I need to see what you're doing there Commented Oct 8, 2013 at 8:27
  • I removed that because my original code was wrong. I have updated with one of your suggestions. Commented Oct 8, 2013 at 9:13
1

Please note this was @EliasVanOotegem original example but there are some obvious steps missing

in the controller i'm reading a few replies as in "I cannot see how this works as i'm getting null" this is because your not correctly keying your object.

i.e.

var data = { name : 'john' };
$.ajax({
 type: "POST",
 url: url,//post how you get this URL please...
 data: {json : data},//jQ will sort this out for you
 success: function(response)
 {
 console.log(response);
 }
 error: function()
 {
 console.log('an error occured');
 console.log(arguments);//get debugging!
 }
});

as you can now see accessing the requerst object like

$request->get('json');

refers to the post key for the json data

answered Sep 18, 2014 at 14:43
0

Is the content what you're trying to retrieve, neither params nor headers.

Try:

$request->getContent();
answered Oct 7, 2013 at 14:09
0

In your case $request->request->get('json') should do.

answered Oct 7, 2013 at 21:12
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.