Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get POST global variable in PHP Symfony 4?

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.

like image 662
Alexandre Martin Avatar asked Feb 26 '19 16:02

Alexandre Martin


3 Answers

The possible solution could be:

$post_data = json_decode($request->getContent(), true);
$date = $post_data['date'];
like image 200
simhumileco Avatar answered Nov 06 '22 21:11

simhumileco


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:

  • http://php.net/manual/en/reserved.variables.post.php
  • https://symfony.com/doc/current/introduction/http_fundamentals.html#symfony-request-object
like image 37
Robert Avatar answered Nov 06 '22 21:11

Robert


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.

like image 38
Javier Ergui Blašković Avatar answered Nov 06 '22 21:11

Javier Ergui Blašković