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?)
jQuery ajax() Method. The jQuery ajax() method provides core functionality of Ajax in jQuery. It sends asynchronous HTTP requests to the server.
The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.
post() methods provide simple tools to send and retrieve data asynchronously from a web server. Both the methods are pretty much identical, apart from one major difference — the $. get() makes Ajax requests using the HTTP GET method, whereas the $. post() makes Ajax requests using the HTTP POST method.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With