1

So I've been following the docs on how to create a search form in Craft and it works fine. But instead of having a results.twig page I would like to have just one index page and get all the results with AJAX. Is there a simple way to accomplish this in Craft? And if so, does anyone have an example?

2

You can create your own search... lets say this is your html

<input type="input" id="searchTags" placeholder="Search">
<input type="button" id="startSearch" value="Go">
<div id="results"></div>

then you have the following script:

$("#startSearch").click(function(){
    var data = {
        action: 'pluginhandle/controller/searchEntries',
        options: $("#searchTags").val()
    };
    $.ajax({
       type: "post",
       url: '/',
       data: data,
       success: function(response){
       // replace content from $("#results") with your new html
       },
    ....
   });
});

Your controller would look like

public function actionSearchEntry(){ 
     $criteria = new ElementCriteriaModel(ElementType::Entry);     
     // build your criteriaModel based on your needs
     $html = $this->renderTemplate('results.twig', array(
         'entries' => $criteria->find()
     ));
     return $this->returnJson($html);
}

your results.twig would be like

{% if entries is defined and entries|length %}
    <ul>
        {% for entry in entries %}
            <li>
                {{ entry.title }}
            </li>
        {% endfor %}
    </ul>
{% endif %}
| improve this answer | |
  • Hi Brad! Thanks for the reply. So I need to create my own plugin to accomplish this? – Billy Sengsey Oct 17 '17 at 10:26
  • The answer was mine - Brad just edited it because I messed up formatting. I`m not sure if there is a craft build in way to accomplish it. Maybe there is and Brad could tell us - but I never used it. You are more flexible if you create your own plugin. All in all I made about 20 pages different pages with craft and none of them without a custom plugin. It is really easy, fast and you have more control. – Robin Schambach Oct 17 '17 at 12:43
  • Hi @Robin Schambach, I'm trying to set up the code in your example. I made a plugin via pluginfactory.io (I've never made a Craft plugin before) and I made the controller just like this example. The JS code gives me an error (Requested page not found. [404]). My JS file is in the public folder and my results.twig page is at the root in my templates folder. Could you please help me out? I would really like this to work – Billy Sengsey Mar 8 '18 at 8:50
  • could you please come here chat.stackexchange.com/rooms/74190/plugin-developement it can have 1000 reasons so it's better to chat in the room – Robin Schambach Mar 8 '18 at 8:58

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.