GET /search/suggest.json

simonski
Shopify Partner
121 8 46

I really hope I can get some starting help here, as I'm a beginner with Liquid and all that comes with it.

I want to implement predictive search in my theme (no App that I want to buy).

I'm struggling right at the beginning.

Please tell me how I can make a call with 

 

GET /search/suggest.json

 

Where do I have to implement this? 

Please, just some starting help would be very much appreciated!

Thank you!

0 Likes
_JB
Shopify Staff
Shopify Staff
750 87 165

Hey @simonski,

 

That endpoint needs to be implemented in your theme, it will be called by the customer's browser and you can use the JSON response to display the relevant products on the storefront. You can see the response in your own store by appending /search/suggest.json?q=a&resources[type]=product to your store's URL in your browser, replace a with your own query.

 

If you haven't already, I recommend taking a look at our predictive search API tutorial and reference docs which contain more information about this API.

JB | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

simonski
Shopify Partner
121 8 46

Hey @_JB 

Thank you for your answer. I try hard to study these "tutorials" for days already, but I have problems to start. I feel like an idiot, I just don't know how I can implement these given codes in my theme in order to see any result in the search-bar, while entering a search query.

Maybe you can give me some hints if you find the time for that. It would be very much appreciated!

I'm very willing to spend time to realize implementing a predective search, but slowly it's getting frustrating. I can't find any information that would make the start easier for me. 

0 Likes
simonski
Shopify Partner
121 8 46

@_JB 

I try to explain what I did, maybe it's easier for you then.

I know I have some real general understanding issues about implementing this predictive search, but I really want to understand and I'd be very thankful for some starting help.

I added this code in my theme.liquid file just above </body>

 

 

<script>
jQuery.getJSON("https://menschenskinder.myshopify.com/search/suggest.json", {
  "q": "goki",
  "resources": {
    "type": "product",
    "limit": 4,
    "options": {
      "unavailable_products": "last",
      "fields": "title,product_type,variants.title"
    }
  }
}).done(function(response) {
  var productSuggestions = response.resources.results.products;

  if (productSuggestions.length > 0) {
    var firstProductSuggestion = productSuggestions[0];

    alert("The title of the first product suggestion is: " + firstProductSuggestion.title);
  }
});
</script>    
{% include 'predictive-search' %}

"q" is not autmoatically created in my code, I guess this would be the next step (if you could also explain how this works, that would be great!).

But I don't even get the "alert" that is inside the code. Nothing happens.

 

Also, I added the following code in a Snippet that I created. It's called "predictive-search.liquid". This code, I guess, would be for handling the answers of the calls. I also have no clue how to implement that.

 

 

<script>
Shopify.PredictiveSearch = (function($) {
  const predictiveSearch = new PredictiveSearch({
  selectors: {
    input: '[data-predictive-search-input="header"]',
    reset: '[data-predictive-search-reset="header"]',
    result: '[data-predictive-search-result="header"]'
  },
  resultTemplateFct: data => {
    return `
      <div class="predictive-search">
        <ul class="predictive-search__list">
          ${data.products.map(
            product => `
            <li data-search-result> <!-- important to add the data-search-result attribute to each result -->
              <img src="${product.image}" alt="${product.title}" />
              <span>${product.title}</span>
            </li>
          `
          )}
        </ul>
      </div>
    `;
  },
  // (a11y) Function to return the number of results that you will display.
  // This will be announced to the user via an aria-live.
  numberOfResultsTemplateFct: data => {
    if (data.products.length === 1) {
      return "one result found";
    } else {
      return "[results_count] results found".replace(
        "[results_count]",
        data.products.length
      );
    }
  },
  // (a11y) Return a string that indicates that we're loading results.
  // This will be announced to the user via an aria-live.
  loadingResultsMessageTemplateFct: () => {
    return "loading";
  },
  onInputFocus: nodes => {
    // You can get a reference to active target
    console.log(nodes.input.id); //-> input
    console.log(nodes.submit.id); //-> submit
    console.log(nodes.result.id); //-> result
  },
  onInputKeyup: nodes => {
    return true; // This will allow the event callback to execute
  },
  onInputBlur: nodes => {
    return false; // This will prevent the event callback to execute
  },
  onInputClear: nodes => {},
  onBeforeKill: nodes => {},
  onBeforeOpen: nodes => {},
  onOpen: nodes => {},
  onBeforeClose: nodes => {},
  onClose: nodes => {},
  onDestroy: nodes => {}
})(jQuery);
 
  Shopify.PredictiveSearch.init();
  
// Public methods
predictiveSearch.open();
predictiveSearch.close();
predictiveSearch.destroy();
predictiveSearch.clearAndClose();
 
</script>

Thank you so much for any help here!

 

simonski
Shopify Partner
121 8 46

Finally I got my first successful response of my JQuery. This was a hard fight.

I'm honestly disappointed of the shopify tutorials and the support here. I don't understand why you guys post a "tutorial" of the Predictive Search and API reference and tell people "Here you can implement Predictive Search, where it doesn't explain anything how to implement that. It would need just a few more explanations and code!!! I know I'm a beginner, but many of your customers are! And giving hope that it would be easy to implement Predictive Search without explaining how is not the way to do. 

I'm talking about this

https://shopify.dev/tutorials/add-predictive-search-to-your-shopify-theme

https://shopify.dev/docs/themes/ajax-api/reference/predictive-search

 

For all the others, not to go almost mad as I did:

In your theme.liquid file, just above your closing body tag </body>, paste this:

<script>
      var q = 'YOUR_SEARCH_EXAMPLE'
      var b = '&resources[type]=product'
      $.ajax('/search/suggest.json?q=' + q + b,{
        type: 'GET',
        dataType: 'json', // added data type
        success: function(response) {
            console.log(response);
          	var productSuggestions = response.resources.results.products;
          	if (productSuggestions.length > 0) {
    			var firstProductSuggestion = productSuggestions[0];
            	alert(firstProductSuggestion.body);
          	}
      	}
      });
</script>

If it's not working, check if your JQuery is loaded correctly:

<script>
    if (window.jQuery) {  
        // jQuery is loaded  
        alert("Yeah!");
    } else {
        // jQuery is not loaded
        alert("Doesn't Work");
    }
</script>

Put all the scripts above your closing body tag.

0 Likes
ChuckD87
Excursionist
14 0 2

@simonski I am also trying to implement Predictive Search, but I am stuck and the Shopify "tutorials" are no help. 

Did you have to edit your search code in addition to adding the scripts? Any help is appreciated. I am using Minimal Theme.

Thanks.

0 Likes
simonski
Shopify Partner
121 8 46

@ChuckD87 

I just added the code to my theme.liquid file. So I didn't modify any given code if that's your question.

There are some tutorials for "autocomplete search", I used these as well in order to put the search results in a new search-results box there.

Good luck!

0 Likes
kuduzovic
Tourist
8 0 1

Hey, so I'm having some trouble here. I created a custom search bar using the code Shopify gave on the search.liquid file.

Here is the code: 

<form class="search" action="/search">
  <input
    type="text"
    placeholder="Search"
    name="q"
    value="{{ search.terms | escape }}"
  />
  <input type="submit" value="Search" />
</form>

The javascript code you gave worked perfectly fine for the normal search bar that comes with shopify, is there any way I could make it work with this search bar as well?

0 Likes