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 :
But $date
is null
.
The possible solution could be:
$post_data = json_decode($request->getContent(), true);
$date = $post_data['date'];
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:
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
.
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