Search code examples
phpjqueryajaxsymfony-3.2

How to display result in success ajax to twig file


I'm new in Symfony! I use symfony 3. I have a search input when i type in search i want display the result in the twig file. I got the correct result send from ajax and i have a problem with display data result from ajax to twig file and use loop in here. Here is my controller

/**
 * @Route("/ajax_search", name="ajax_search", options={"expose"=true})
 */
public function ajaxSearchAction( Request $request)
{
    $string = $request->get('search_items');
    $users = $this->getDoctrine()
        ->getRepository('AppBundle:Item')
        ->findEntitiesByString($string);

    $encoders = array(new XmlEncoder(), new JsonEncoder());
    $normalizers = array(new GetSetMethodNormalizer());
    $serializer = new Serializer($normalizers, $encoders);

    $jsonContent = $serializer->serialize($users, 'json');
    $response = new Response($jsonContent);

    return $response;
}

ajax :

$(document).ready(function () {
    $("#search_items").keyup(function () {
        var q = $("#search_items").val();
        var url = '../ajax_search?search_items=' + q;
        $.ajax({
            url: url ,
            type: 'POST',
            dataType: 'json',
            data: {q: q},
            success: function(data){
                var result = JSON.stringify(data);
                $('.test').html(result); //return correct data

            }
        });
    });
});

and my twig

<input type="text" name="search" placeholder="search" id="search_items"/>
<div class="test"></div>//i want to get data and use loop in here

Solution

  • In your Action to render the twig template you need to pass your code you want to use in your template as following:

            return $this->render(
            'yourTemplate.html.twig',
            array(
                'yourKey' => callYourFunctionToGetTheData()
            )
        );
    

    In Twig you can address your data like this:

    <div>{{ yourKey }}</div>
    

    In Twig are arrays, objects and just "normal" values possible e.g integers,strings and so one.

    Hope that this will help you!

    Check the twig documentation for more Twig Documentation

    Greetings