4

Does anyone have an example how I would implement search results that appear in a popup on the same form (without redirecting to a results page). The idea would be that as they start to type in the search bar, after a delay I'd show a popup with a few results.

I'm good on the jS, popup part. The part i don't know about is how i would call craft cms dynamically on the same page to get the results (would i do this with JS or with the form tag, can i make the request with JSON/Ajax?). All the examples show the form directing to a results page.

Anyone have any suggestions

6

You can request any template via ajax using jQuery. jQuery would essentially listen for onChange events from the search field and ajax load a template that looped through the search results.

The template that you request can even be the default full search results page, with a conditional that determines which part of the template gets returned if the request is ajax.

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).order('score') %}

{% if not craft.request.isAjax %}
    {# Full page results content can go here #}
    <h1>Search Results</h1>
    <div class="search-results">
        <ul>
        {% for entry in entries %}
            <li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
        {% endfor %}
        </ul>
    </div>
{% endif %}

{% if craft.request.isAjax %}
    {# Drop-down results can go here. And inserted into DOM via jquery. #}
    {% for entry in entries %}
        <li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
    {% endfor %}
{% endif %}

jQuery can then insert the results of the ajax call using an html element selector. See the jquery documentation for more information on using .load or .ajax.

You will also probably want to put the {% set entries ... %} inside the if isAjax statements so that you can limit the results, or implement pagination, for the drop down vs the full page.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.