Skip to content Skip to sidebar Skip to footer

Live Search In Symfony4 Using Ajax+js

i want to implement a live search under symfony 4 but im stuck. i hope your help friends. my controller /** * @Route('/search', name='search') */ public function searchAction(Re

Solution 1:

You're close. :) Personally I'd do something like this.

Action function:

/**
 * Search action.
 * @Route("/search/{search}", name="search")
 * @param  Request               $request Request instance
 * @param  string                $search  Search term
 * @return Response|JsonResponse          Response instance
 */publicfunctionsearchAction(Request $request, string$search)
{
    if (!$request->isXmlHttpRequest()) {
        return$this->render("search.html.twig");
    }

    if (!$searchTerm = trim($request->query->get("search", $search))) {
        returnnew JsonResponse(["error" => "Search term not specified."], Response::HTTP_BAD_REQUEST);
    }

    $em = $this->getDoctrine()->getManager();
    if (!($results = $em->getRepository(User::class)->findOneByEmail($searchTerm))) {
        returnnew JsonResponse(["error" => "No results found."], Response::HTTP_NOT_FOUND);
    }

    returnnew JsonResponse([
        "html" => $this->renderView("search.ajax.twig", ["results" => $results]),
    ]);
}

Your search.html.twig should not contain the for loop with the results, but instead should just be this instead of the for loop:

<form id="search-form"class="example-wrapper" role="search" method="get" action="{{ path('search') }}">
    <div><inputtype="text"class="form-control"name="search"><buttontype="submit"class="btn btn-success"name="sub">search</button></div></form><divid="search-results"class="example-wrapper"></div><scripttype="text/javascript"><!--

jQuery(document).ready(function($){

    $('#search-form').submit(function(e){

        e.preventDefault();
        $('#search-results').html("");

        $.get("{{ path('search') }}/" + input, function(data, textStatus, xhr){

            if ("object" !== typeof data || null === data) {
                alert("Unexpected response from server.");
                return;
            }

            if (!data.hasOwnProperty("html") || typeof data.html != "string" || (data.html = data.html.trim()).length < 1) {
                alert("Empty response from server.");
                return;
            }

            $('#search-results').html(data.html);

        }).fail(function(xhr, textStatus, errorThrown){

            var error = "Unknown error occurred.";
            if ("object" === typeof xhr && null !== xhr && xhr.hasOwnProperty("responseJSON") && "object" === typeof xhr.responseJSON && xhr.responseJSON.hasOwnProperty("error") && "string" === typeof xhr.responseJSON.error && xhr.responseJSON.error.trim().length >= 1) {
                error = xhr.responseJSON.error.trim();
            } elseif ("string" === typeof errorThrown && errorThrown.trim().length >= 1) {
                error = errorThrown.trim();
            }

            alert(error);

        });

    });

});

--></script>

You should then have search.ajax.html in the same folder as search.html.twig to contain the results loop. This should consist of only this:

{% if results is defined and results is iterable and results|length >= 1 %}
    {% for result in results %}
        <pstyle="display:inline-block;width:200px;">{{ result.fullname }}</p><pstyle="display:inline-block;width:100px;">{{ result.username }}</p><pstyle="display:inline-block;width:300px;">{{ result.email }}</p><pstyle="display:inline-block;width:120px;">{{ result.roles[0] }}</p>
    {% endfor %}
{% endif %}

Post a Comment for "Live Search In Symfony4 Using Ajax+js"