Metio_1993 Metio_1993 - 11 months ago 61
Ajax Question

Can't send data to the Controller with a POST method Symfony3

I have a POST method Jquery. Ajax and I can't send my data to the controller, I have tried every solution on the net, but no result.......

My JavaScript


var data1 = {request : $('#request').val()};
type: "POST",
url: "/Manufacturer",
data: data1,
success: function(dataBack) {

contentType: "application/json",
dataType: 'json'

MY controller

public function indexAction(Request $request)
//$name = $request->request->get('data');
//return new Response($name);//or do whatever you want with the sent value
$name = $request->request->get('data1');
If($name == 1)
return new Response('Yeap');
return new Response(';(');

return $this->render('MyIndex/Manufacturer_LIST.html.twig' );

HEre is my Console ::

And my response is as it's obvious ";("

Answer Source

First you need to install FOSJsRoutingBundle to be able to "expose" your Symfony routes into the javascript code. Follow the steps in the official documentation.

Then, in your twig template if you have a form like:

    <input type="text" id="name"> <br>
    <button type="submit" id="submitForm">Submit</button>

your js code could look liks this:

    var name = $('#name').val();
        method: 'POST',
        url: Routing.generate('Manufacturer_LIST');
        // OR: url: "/Manufacturer", if you don't want to install FOSJsRoutingBundle
        data: { name:name }
    }).fail(function(XMLHttpRequest, textStatus, errorThrown){
        console.log(textStatus + ' ' + errorThrown);

And in your controller:

 * @Route("/Manufacturer", name="Manufacturer_LIST", options={"expose"=true})
public function indexAction(Request $request){
        $name = $request->request->get('name');
        return new Response($name);//or do whatever you want with the sent value
    return $this->redirectToRoute('homepage');