In my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller : I'm using Jquery and Ajax to send my variable to the controller but I cannot have access to my variables. There is no problem with my Ajax Request, I checked via Symfony profiler and the request is sent correctly but for some reason the controller can't even detect the Ajax request.
Here is my controller:
public function saisieAction(Request $request)
{
$user = $this->getUser();
$thisyear = date("Y");
$em = $this->getDoctrine()->getManager();
// Create the form
$form = $this->get('form.factory')->createBuilder(FormType::class)
->add('ndf', CollectionType::class, array(
'entry_type' => NoteDeFraisType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
))
->getForm();
// if the form has been submited
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
if($request->isXMLHttpRequest()){
//After some code debuging, this is never
//executed
$month = $request->get('month');
$year = $request->get('year');
$sub_date = $month .'/' .$year;
}
$notesDeFrais = $form['ndf']->getData();
foreach ($notesDeFrais as $ndf) {
$ndf->setUser($user);
$ndf->setMonth($sub_date);
$em->persist($ndf);
}
$em->flush();
}
return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
array(
'year' => $thisyear, 'form' => $form->createView()
));
}
And the script inside my saisie.html.twig view:
$(".month").click(function() {
var click = $(this);
var month = click.val();
var year = $("#years").val();
$.post("{{ path('avaliance_platform_saisie') }}",
{ 'month' : month,
'year' : year
},
function (data,status) {
alert('Data sent');
});
});