How to Render Shopify AJAX Predictive Search for Products

How to Render Shopify AJAX Predictive Search for Products

Predictive search helps customers find products quickly by displaying suggestions as they type. Here’s how to implement Shopify AJAX predictive search using JavaScript and Shopify’s search API.

1. Create a Search Input Field

Add a search input box in your Shopify theme where users can enter search queries.

Code:

<input type="text" id="search-input" placeholder="Search for products...">
<ul id="search-results"></ul>

2. Implement AJAX Predictive Search

Use JavaScript to fetch search results dynamically.

Code:

document.getElementById('search-input').addEventListener('input', function() {
    let query = this.value;
    if (query.length > 2) { // Start searching after 3 characters
        fetch(`/search/suggest.json?q=${query}&resources[type]=product`)
        .then(response => response.json())
        .then(data => {
            let results = data.resources.results.products;
            let resultContainer = document.getElementById('search-results');
            resultContainer.innerHTML = results.map(product => 
                `<li><a href="${product.url}">${product.title}</a></li>`
            ).join('');
        });
    }
});

Explanation:

  • Listens for input in the search box.
  • Calls Shopify’s search API to get product suggestions.
  • Updates the results dynamically without page reload.

3. Styling the Search Results

Improve the appearance of the search results with CSS.

Code:

#search-results {
    list-style: none;
    padding: 0;
    margin-top: 5px;
    background: #fff;
    border: 1px solid #ddd;
}
#search-results li {
    padding: 10px;
    border-bottom: 1px solid #ddd;
}
#search-results li:hover {
    background: #f0f0f0;
}

4. Enhancing with Product Images

Modify the JavaScript to include product images in the results.

Updated Code:

document.getElementById('search-input').addEventListener('input', function() {
    let query = this.value;
    if (query.length > 2) {
        fetch(`/search/suggest.json?q=${query}&resources[type]=product`)
        .then(response => response.json())
        .then(data => {
            let results = data.resources.results.products;
            let resultContainer = document.getElementById('search-results');
            resultContainer.innerHTML = results.map(product => 
                `<li>
                    <img src="${product.image}" alt="${product.title}" width="50">
                    <a href="${product.url}">${product.title}</a>
                </li>`
            ).join('');
        });
    }
});

Conclusion

By implementing AJAX predictive search, you can improve product discovery and enhance the shopping experience on your Shopify store. This method ensures users receive relevant search suggestions in real time.

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top