0

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

9
  • So you're saying that Twig isn't replacing the {{ path('av_platform_saisie') }} correctly? Commented May 31, 2019 at 16:20
  • No, the path is correct. I tried the same Ajax request from another view and it works fine Commented May 31, 2019 at 16:24
  • I don't understand what you mean by "I can't access it from my controller" Commented May 31, 2019 at 16:25
  • Basically, I want to get the js variables I sent via Ajax php $month = $request->get('month'); $year = $request->get('year'); Commented May 31, 2019 at 16:28
  • Did you check the network tab in a browser's dev tools? Commented May 31, 2019 at 20:47

4 Answers 4

3

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');
Sign up to request clarification or add additional context in comments.

4 Comments

I already tested the php $request->request->get('parameter') syntax but it's not working either. As I said in my original post, the exact same code is working my javascript in on a view that is not rendered by my controller and I can't get why
I'm importing the right Request class. I'll try to figure out how getContent () method works, thank you for your help
@AliT what I wrote above is the proper way to get your POST parameters. If it doesn't works, it mean the promblem is elsewhere. Like ehymel said, you should move url into ajax options. It's most common. Which Symfony version are you using? It helps a lot to know this. You should edit your question and state which version of Symfony you're using.
I moved the url into ajax options but nothing new and my Ajax request is correctly sent, I already checked on symfony profiler. I'm using the version 3.4 of symfony, I will edit my original post to precise it, thanks
0

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;

3 Comments

or maybe you'll have to use: $data = json_decode($request->getContent(),true); And then you could access: $year = $data['year']; Not sure about having to use json_decode or not to get your associative array ... my Symfony is a bit rusty :D
I'm using symfony 3 and as I said in my original post, the exact same code is working my javascript in on a view that is not rendered by my controller. But I will explore the $request->getContent() suggestion, thanks
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;
0

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){}
     });
});

1 Comment

I did it but still the same issue, my ajax request is correctly sent. The problem is not in the javascript
-1

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')

1 Comment

Yes, there is no problem with the path. Twig path function works fine if you have no parameters to pass. I used FosJsRoutingBundle on other scripts :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.