I'm trying to use AJAX to run my controller code after a button is clicked. From what I gathered, this is what you should use AJAX for...it sends a response from the front end to the back end and then generates a json response.
However I cannot figure out how to properly do this. I'm unsure on how to get AJAX to run the controller code on success.
All I have been able to do is show the table upon success but I don't want the controller code to run until button is clicked, as that is the point of the AJAX .
Symfony does not appear to have a documentation on this: http://symfony.com/legacy/doc/book/1_0/en/11-Ajax-Integration
And these stack overflow question/answers are too old for my use or do not help me:
How to integrate Ajax with Symfony2
How to make a POST Ajax request with Symfony and Jquery
twig:
<button id="begin-check" type="button">Run Test</button>
<table class="stab">
<thead>
<tr>
<th style="text-align: center">Ang</th>
<th style="text-align: center">Lat</th>
</tr>
<tr>
<th>Name & Age</th>
<th>Name & Age</th>
</tr>
</thead>
<tbody>
{% for person in persons %}
<tr>
<td>
<a href="{{ path('users_edit', { 'id': person[0] }) }}">
{{ person[1] }}, {{ person[2] }}
</a>
</td>
<td>
{% if person[7] == 'Moe' %}
<a href="{{ path('edit', { 'id': person[6] }) }}">
{% else %}
<a href="{{ path('low_edit', { 'id': person[8] }) }}">
{% endif %}
{{ person[4] }}, {{ person[5] }}
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
AJAX:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', "#begin-check", function(e){
console.log('You have clicked');
e.preventDefault();
$.ajax({
method: 'POST',
url: "{{ path('control_check') }}",
data: { //research what to put here
},
success: function(responseData){
//run the controller code
//Show HTML table
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
},
})
});
});
</script>
In controller:
/**
*
* @Route("/control", name="control_check")
* @Template()
*/
public function controlCheckAction()
{
$request = $this->get('request');
$em = $this->getDoctrine()->getManager();
$persons = array();
//more code
return new JsonResponse(array('persons' => $persons));
}