im learning Symfony and now trying to connect Ajax with Symfony. I put Ajax between javascript block in twig and put really simple function in controller file to check whether it is working, but found out it's not working. Doesn't show alert inside Ajax, and not showing dump($r) in console as well.
this is my Ajax script in twig file '''
{%block javascripts %}
<script language = "javascript">
$(document).ready(function () {
$("#customize").on("click", function (event) {
$.ajax({
url: "{{ 'test/ajax' }}",
type: 'POST',
async: true,
dataType: 'json',
data:{
id:1,
text: 'hello'
}
}).done(function(data) {
alert('yes');
}).fail(function() {
alert('no');
})
});
});
</script>
{%endblock%}
'''
this is the Anker connected to Ajax. '''
{{form_start(form)}}
{{form_widget(form)}}
{{form_end(form)}}
<a href="#" id="customize" name="customize" >Customize</a>
'''
this is the controller file '''
/**
* @Route("/test/ajax", name="ajax_edit")
*/
public function ajaxAction(Request $request){
$r = $request->request->get('data');
dump($r);
}
'''
I guess Anker is not responding even though I clicked it. but I don't know how to fix this problem..
CodePudding user response:
To ensure you have the good URL in your TWIG template, you should used the path()
method to generate your URL using the route name:
$(document).ready(function () {
$("#customize").on("click", function (event) {
$.ajax({
url: "{{ path('ajax_edit') }}",
type: 'POST',
async: true,
dataType: 'json',
data: {
id:1,
text: 'hello'
}
}).done(function(data) {
alert('yes');
}).fail(function() {
alert('no');
})
});
});
And as Bossman said, your route must return a JsonResponse:
/**
* @Route("/test/ajax", name="ajax_edit")
*/
public function ajaxAction(Request $request)
{
$r = $request->request->get('data');
return $this->json($r);
}
And of course, if you want to check the response content, you should open you browser console, in network tab and check the request response. Open the console on correct tab before click on button #customize.