angezanetti angezanetti - 2 years ago 149
Ajax Question

How to make a POST Ajax request with Symfony and Jquery

I need to store some map parameter in my symfony project, to do this i need to implement some Ajax in my view which will be able to pass some info to the controller.

I read the docs, try to write some code but i can't make it works. And Ajax is really painfull to debug.
Here is the controller part :

/**
* @Route("/ajax", name="_recherche_ajax")
*/
public function ajaxAction()
{
$isAjax = $this->get('Request')->isXMLHttpRequest();
if ($isAjax) {
return new Response('This is ajax response');
}
return new Response('This is not ajax!', 400);
}


And the JS :

map.on('zoomend', function(e) {
// use callback e variable
console.log('zoom: ' + e.target.getZoom());

$.ajax({
type: "POST",
url: "/recherche/ajax",
data: {
zoom: e.target.getZoom()
},
dataType: "json",
success: function(response) {
console.log(response);
}
});

});


I check the url
recherche/ajax
it does exist and return the 'This is not Ajax' as expected. But the console.log does not return any value...

Is that the right way to do this ?

EDIT :
It looks like the controller can't handle POST Request. I tried to modify the annotations to :

/**
* @Route("/ajax", name="_recherche_ajax")
* @Method({"GET", "POST"})
*/


But it returns :

([Semantical Error] The annotation "@Method" in method MySite\SiteBundle\Controller\RechercheController::ajaxAction() was never imported. Did you maybe forget to add a "use" statement for this annotation?)

Answer Source

Try this,

/**                                                                                   
 * @Route("/ajax", name="_recherche_ajax")
 */
public function ajaxAction(Request $request)    
{
    if ($request->isXMLHttpRequest()) {         
        return new JsonResponse(array('data' => 'this is a json response'));
    }

    return new Response('This is not ajax!', 400);
}

In case of you sending an Ajax request, you need to return json/plaintext/xml data, and not a whole Response object.

PS: Do not forget to add use statment for Request and JsonResponse

EDIT : As the error message you added says, you need to import the annotation @Method by using :

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download