17

I have a very strange problem getting the result of a POST global variable in Symfony 4.

I tried this way:

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

This is how I actually send the AJAX request when the Calendar input's date changed:

onSelect: function(date, instance) {
    $.ajax({
      url : 'home',
      type : 'POST',
      data : {'date':date},
      dataType : 'html',
      success : function(code_html, statut){
        console.log(statut);
      },

      error : function(resultat, statut, erreur){
      
      },

      complete : function(resultat, statut){

      }          
    });

The onSelect callback successfully receive the date value I want.

And this result shows the 200 success code with right values for the date variable :

profiler screenshot

But $date is null.

yivi
  • 42,438
  • 18
  • 116
  • 138
Alexandre Martin
  • 1,472
  • 5
  • 14
  • 27
  • 1
    Sorry, but what's your question? What bit are you saying isn't working? – Jonnix Feb 26 '19 at 16:08
  • 2
    What do you get if you `var_dump($_POST)`? Given your profiler page shows the POST var is there, but it also shows you're posting to /, which isn't the same as what the AJAX request is doing? Have you looked at the network tab of your browser tools to see what is actually getting sent to `home` and what the response is? – Jonnix Feb 26 '19 at 16:20
  • 1
    `data : {'date':date},` change to `data : {date:date},` I think your post key will no longer be `'date'` and it will become `date` and your code will work – RiggsFolly Feb 26 '19 at 16:38
  • 2
    @RiggsFolly The result will be the same. It works both ways – KubiRoazhon Feb 26 '19 at 16:41
  • @KubiRoazhon Ok, had a similiar sort of issue somewhere in that past, but cant quite remember if it is relevant here so I thought I would stick it in the pot as a comment – RiggsFolly Feb 26 '19 at 16:43
  • Try doing a `var_dump()` on `$request->request->all()` to see all the post values. – DEarTh Mar 01 '19 at 09:23

5 Answers5

25

There is no problem with headers or anything like that in your code, and the jQuery request is correct as it is (I tested your code).

The problem might be with your PHP code, which is not present in your question.

If you are injecting the Request object correctly, you can easily use get() to retrieve the post variables.

For example:

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class VeryDefaultController extends AbstractController
{

   /**
   * @Route("/very/default", name="very_default")
   * @param Request $request
   *
   * @return \Symfony\Component\HttpFoundation\Response
   */
   public function index(Request $request)
   { 
       $date = $request->get('date');
   }
}

In your example you are doing $request->request->get('date') which is fine for a POST or PUT request, but it's probably failing because you are not injecting the Request object correctly.

The above code is tested with your jQuery AJAX POST request, and it works. There is nothing inherently wrong in that part. And it is perfectly possible to access POST variables using get().

crmpicco
  • 16,605
  • 26
  • 134
  • 210
yivi
  • 42,438
  • 18
  • 116
  • 138
  • As the profiler shows the post variable and the success code, I think the PHP part is correct. POST variable is sent, but I can't get it. – Alexandre Martin Mar 06 '19 at 10:52
  • The POST variable is sent, and you can get it. It's simply you are not getting it correctly. In the only code you show, you do `$request->request->get()`, which doesn't appear to make a lot of sense. The above code is tested, and it works. – yivi Mar 06 '19 at 10:54
  • 1
    There is no valuable solutions, I still have the problem – Alexandre Martin Mar 07 '19 at 16:29
  • @AlexandreMartin then something is missing from your question. With your jquery code and the code from my answer, it works. If you don’t provide the missing pieces, nobody can help you. – yivi Mar 07 '19 at 16:38
  • $request->get('parameter') will allow you just to get the get variables. – TaouBen Aug 28 '19 at 07:58
  • 1
    I do not understand what you mean, @Taou. Something I should correct in my answer? – yivi Aug 28 '19 at 08:09
  • I think so, your answer did not xork for me, if my variable is a get variable then it works, but post variables worked for me by using getContent() method and then parsing the response with json decode, I am using symfony 4. – TaouBen Aug 28 '19 at 20:55
  • 1
    @TaouBen `Request::get()` works both for `GET` and `POST` parameters. What you are describing is getting the _request body_; which is not what this question was trying to do. (Again, I tested the code with their specific AJAX request). – yivi Aug 29 '19 at 07:11
15

you are sending a JSON string, hence you'll need to use:

$content = $request->getContent();

and then you'll need to parse it with json_decode.

yivi
  • 42,438
  • 18
  • 116
  • 138
10

The possible solution could be:

$post_data = json_decode($request->getContent(), true);
$date = $post_data['date'];
simhumileco
  • 31,877
  • 16
  • 137
  • 115
6

The problem you may face is related with Accept HTML header that PHP uses to convert the variables from post body to $_POST and Symfony uses $_POST to fill the request object data.

To get this behaviour you need to use header application/x-www-form-urlencoded or multipart/form-data.

To check if that's actually the case you need to use the code:

dump($request->getContent());

If it's filled with variables then it means PHP doesn't convert them to $_POST because of MIME mismatch, if not then it means that request is incorrect.

Normal approach to access post variable is:

public function index(Request $request) 
{
    dump($request->getContent()); // get raw body of http request 
    dump($request->request->get('date')); //get converted variable date by php and then by symfony
}

Useful links to check:

yivi
  • 42,438
  • 18
  • 116
  • 138
Robert
  • 19,800
  • 5
  • 55
  • 85
  • in my case it was related, to a missing `Content-Type` header, the value for the header is `application/x-www-form-urlencoded` – Souhaieb Feb 07 '23 at 13:35
-1

Try adding the content type, stringify your json data and use traditional serialization, like this:

onSelect: function(date, instance) {
var data = {'date':date};
$.ajax({
  url : 'home',
  type : 'POST',
  data : JSON.stringify(data),
  contentType: "application/json; charset=utf-8",
  traditional: true,
  dataType : 'html',
  success : function(code_html, statut){
    console.log(statut);
  },

  error : function(resultat, statut, erreur){

  },

  complete : function(resultat, statut){

  }          
});

As you are not posting your controller code I suggest being sure that:

  • You have a use statement like \Symfony\Component\HttpFoundation\Request;
  • You are injecting the Request like public function post( Request $request )
  • You are reading your data like $data = json_decode( $request->getContent(), true);. On this example you will have the data as an assoc array.
user2226755
  • 12,494
  • 5
  • 50
  • 73
Francisco Félix
  • 2,413
  • 13
  • 16