0

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

            });
            

        });
Ali T
  • 9
  • 3
  • From your comments in the script, I take it that you have verified that `if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {` is passing? – Tim Morton Jun 08 '19 at 16:51
  • Yes, it is. I get the error ```php Undefined variable: sub_date ``` because my code inside ```if($request->isXMLHttpRequest()){}``` is not executed – Ali T Jun 08 '19 at 16:56
  • According to the docs, `public function isXmlHttpRequest() { return 'XMLHttpRequest' == $this->headers->get('X-Requested-With'); }`. Verify that this header is being sent... – Tim Morton Jun 08 '19 at 16:58
  • Just checked and that's the case... – Ali T Jun 08 '19 at 17:03
  • also, make sure that the domain is exactly the same, otherwise the `X-Requested-With` won't be sent https://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header – Tim Morton Jun 08 '19 at 17:04
  • Hmm I will verify but I'm not sure that's the problem: I actually tried an alternative way to by-pass the problem by sending my data to another view and it actually worked with the exact same code but I got other sort of problems :\ – Ali T Jun 08 '19 at 17:10

2 Answers2

0

I don't really understand what is the server language here but I think in your post request you are missing. contentType (type of data you are sending to the server) and dataType (The type of data that you're expecting back from the server)

contentType:"application/json; charset=utf-8", dataType:"json",

Also, check whether your controller action method is configured to receive post http data.

Sandeep Ingale
  • 408
  • 4
  • 8
0

From the source code:

/**
 * Returns true if the request is a XMLHttpRequest.
 *
 * It works if your JavaScript library sets an X-Requested-With HTTP header.
 * It is known to work with common JavaScript frameworks:
 *
 * @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
 *
 * @return bool true if the request is an XMLHttpRequest, false otherwise
 */
public function isXmlHttpRequest()
{
    return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}

Therefore, the problem is with the AJAX request not having this header. JQuery should put it in automatically, unless there is a reason to exclude it. A cross-domain request would be one such reason.

It is possible to manually insert the header (but only use this for debugging):

  $.post("{{ path('avaliance_platform_saisie') }}",
        { 'month' : month,
          'year' : year
        },
        headers: {'X-Requested-With': 'XMLHttpRequest'},

        function (data,status) {
            alert('Data sent');

        });


    });
Tim Morton
  • 2,614
  • 1
  • 15
  • 23
  • I already checked that my Ajax request has the 'XMLHttpRequest' header. I added headers: {'X-Requested-With': 'XMLHttpRequest'} on my request but nothing changed – Ali T Jun 09 '19 at 11:27
  • Your rationale in saying the conditional is not taken makes good sense to me, but it sounds like we’re making a bad assumption about a variable value somewhere. Var dump the isxmlhttprequest method and verify it’s false, var dump $this->headers->get... – Tim Morton Jun 09 '19 at 13:04
  • It seems you're right: var_dump($request->isXmlHttpRequest()) gives false as expected and $request->headers->get('X-Requested-With') is null even while adding headers: {'X-Requested-With': 'XMLHttpRequest'} to the Ajax method... – Ali T Jun 09 '19 at 16:03
  • Next step, use the browser's console to inspect the packet going out. In the meantime, is there a reason for assigning the month and day only when it's an ajax request? If it weren't an ajax request, it would fail ungracefully with the same error you're getting now. So what's the purpose in it? – Tim Morton Jun 09 '19 at 20:58
  • There is not real a purpose on it, I added the condition just to see if the ajax request is received by the controller. What do you mean by "inspect the packet going out" ? How I could do that ? Can you please elaborate – Ali T Jun 10 '19 at 18:34
  • in chrome, right click in page and select "inspect" then click on "network" tab. Should be similar in FF and IE. – Tim Morton Jun 10 '19 at 22:27