Metio_1993 Metio_1993 - 28 days ago 12
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

$(document).ready(function(){
$('#submitForm').click(function(){

var data1 = {request : $('#request').val()};
$.ajax({
type: "POST",
url: "/Manufacturer",
data: data1,
success: function(dataBack) {
console.log(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
if($request->isXmlHttpRequest()){
$name = $request->request->get('data1');
If($name == 1)
{
return new Response('Yeap');
}
else
{
return new Response(';(');
}

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


HEre is my Console ::

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

Answer

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:

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

your js code could look liks this:

$('#submitForm').click(function(e){
    e.preventDefault();
    var name = $('#name').val();
    $.ajax({
        method: 'POST',
        url: Routing.generate('Manufacturer_LIST');
        // OR: url: "/Manufacturer", if you don't want to install FOSJsRoutingBundle
        data: { name:name }
    }).done(function(msg){
        console.log(msg);
    }).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){
    if($request->isXmlHttpRequest()){
        $name = $request->request->get('name');
        return new Response($name);//or do whatever you want with the sent value
    }
    return $this->redirectToRoute('homepage');
}
Comments