Fares Omrani Fares Omrani - 11 days ago 6
jQuery Question

Symfony: Search field on table with ajax

I'm new in Symfony. I wanna create a table with a search field for every column.
I used ajax to send search value to the controller.
My problem is I don't know the type of result that must return the controller (HTML or Json) and how to display the result on my twig table

My JS function:

$.ajax({
url: "{{ path('demande_search') }}",
type: "GET",
data: 'filter='+$("#f").val(),
success: function(data){
$("#table_id").html(data);
}
});


My table in the twig file:

<table id="table_id">
<thead>

</thead>
<tbody>
{% for demande in demandes %}
<tr>
<td>{{ demande.did }}</td>
</tr>
{% endfor %}
</tbody>
</table>


My controller that returns the result of search

<?php
/**
* Lists searched entities.
*
* @Route("/search", name="test_search")
* @Method("GET")
*/
public function searchAction(Request $request)
{
$query = $em->createQuery(
'SELECT t
FROM AppBundle:Test t'
);
$categorias = $query->getArrayResult();

$response = new Response(json_encode($categorias));
$response->headers->set('Content-Type', 'application/json');

return $response;
}
?>


Thank you in advance

Answer

Your Controller should output the ready rendered table. Move or copy only the table into a new twig file. Let the Controller create the table and give it back to jQuery:

 /**
 * Lists searched entities.
 *
 * @Route("/search", name="test_search")
 * @Method("GET")
 */
public function searchAction(Request $request)
{
    $query = $em->createQuery(
        'SELECT t
        FROM AppBundle:Test t'
    );
    $categorias = $query->getArrayResult();

    return $this->render('AppBundle:table.html.twig', ['categorias' => $categorias]);
}

Then in your AJAX request you can replace the table with the new table from controller:

$.ajax({
    url: "{{ path('demande_search') }}",
    type: "GET", 
    data: 'filter='+$("#f").val(),
    success: function(data){
        $("#table_id").replaceWith(data);
    }
});
Comments