简体   繁体   中英

Cannot access javascript variable inside symfony controller

On my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller containing a form : I used Jquery and Ajax to send my variable to the right route but for some reason I cannot access it from my controller.

Here is the script part in my twig view:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});

And 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()){

            $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()
        ));
}

The weird thing is: I tried to send my js variables from a new Twig view that is not rendered by my controller and it's working just fine with exactly the same code so maybe it is a normal behavior ?

EDIT: I did some debugging and actually and the code inside my if($request->isXMLHttpRequest()) is not executed

You're not using the right syntax to get your parameters, this is how it should be :

if($request->isXMLHttpRequest()) {
    $month=$request->request->get('month');
    $year=$request->request->get('year');
    $sub_date=$month .'/' .$year;
}

And in case you want to get GET parametrers, it's this :

$request->query->get('get_param');

You have to get the content of the Request correctly.

Depending on your version of Symfony, other answers might not work and you might have to use:

$request->getContent();

To have access to the associative array containing your data.

(Edit to add my comment): If it does not work, the only other thing on top of my head would be that your IDE autoimport would have imported the wrong "Request" class in your controller ? Make sure you use --> use Symfony\\Component\\HttpFoundation\\Request;

Put your url inside the array passed to ajax with, like so:

 $(".month").click(function() {
     var click = $(this);
     var month = click.val();
     var year = $("#years").val();

     $.ajax({
         url: "{{ path('av_platform_saisie') }}",
         type: 'POST',
         data: { 'month': month, 
                 'year': year
               },
         success: function (data) {
             alert('OK');
         },
         error : function(jqXHR, textStatus, errorThrown){}
     });
});

Did you checked the source code of the form, what is the value of action attribute? I think you can't add the js url for that AJAX request as you did. Ideally, install FosJsRoutingBundle , and modify as:

url: Routing.generate('av_platform_saisie')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM