Hopiant Private Limited

Hire Dedicated Shopify Developers! Contact Us

Integrating GraphQL Queries in Shopify Liquid Themes Using AJAX and jQuery

Table of Contents

Introduction

Shopify, a leading e-commerce platform, offers a robust templating language known as Liquid for designing store themes.

However, one limitation that developers often encounter is the inability to directly use GraphQL queries within Shopify Liquid themes.

This article explores a workaround to this limitation by utilizing AJAX and jQuery to fetch data from the Shopify Storefront API.

Understanding the Limitation

Shopify Liquid is a powerful tool, but it has its constraints. It cannot execute GraphQL queries directly.

This is primarily because Liquid is designed to handle Shopify’s backend logic and not to interact with APIs in the way GraphQL requires.

The Solution: AJAX with GraphQL in Shopify

To overcome this limitation, we can use AJAX, a web development technique for creating asynchronous web applications, in combination with jQuery, a fast and concise JavaScript library.

By doing so, we can make requests to the Shopify Storefront API from within the Liquid theme.

Implementing the AJAX Call

Here’s a basic example of how to implement this:

1. Include jQuery : First, include jQuery in your Liquid theme.

				
					<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

				
			

2. Craft the AJAX Request : Use jQuery to make an AJAX request to the Shopify Storefront API.

				
					<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $.ajax({
    url: 'https://your-shop-name.myshopify.com/api/2021-07/graphql.json',
    method: 'post',
    headers: {
      'X-Shopify-Storefront-Access-Token': 'your-storefront-access-token',
      'Content-Type': 'application/json',
    },
    data: JSON.stringify({
      query: `
        {
          collectionByHandle(handle: "your-collection-handle") {
            products(first: 10) {
              edges {
                node {
                  id
                  title
                  description
                  images(first: 1) {
                    edges {
                      node {
                        originalSrc
                      }
                    }
                  }
                  variants(first: 1) {
                    edges {
                      node {
                        id
                        priceV2 {
                          amount
                          currencyCode
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      `,
    }),
    success: function(response) {
      const products = response.data.collectionByHandle.products.edges.map(({ node }) => ({
        id: node.id,
        title: node.title,
        description: node.description,
        image: node.images.edges[0]?.node.originalSrc,
        variantId: node.variants.edges[0]?.node.id,
        price: node.variants.edges[0]?.node.priceV2.amount,
        currency: node.variants.edges[0]?.node.priceV2.currencyCode,
      }));

      // Now you can use the products data in your theme
      console.log(products);
    },
  });
});
</script>
				
			

Replace the URL, access token, and GraphQL query with your specific details. You can install this GraphQL app https://shopify-graphiql-app.shopifycloud.com/login to set up a quick playground on your store.

3. Process the Response: In the success function, process the response to extract and use the data as needed.

Example: Fetching and Displaying Products

The following code fetches the first 10 products from a specified collection and displays them:

1. HTML Structure :

				
					<div id="products"></div>

				
			

2. AJAX Request and Dynamic HTML Creation :

				
					<script>
// ...AJAX setup as before...
success: function(response) {
  const products = // ...extract products from response...

  // Create HTML elements for each product
  const productElements = products.map(product => `
    <div class="product">
      <img decoding="async" src="${product.image}" alt="${product.title}">
      <h2>${product.title}</h2>
      <p>${product.description}</p>
      <p>${product.currency} ${product.price}</p>
    </div>
  `);

  // Insert the product elements into the #products div
  $('#products').html(productElements.join(''));
},
</script>

				
			

This approach dynamically creates HTML elements based on the data fetched from the API and inserts them into the Shopify Liquid theme.

Security Considerations

While this method is effective, it’s crucial to address the security aspect of using Storefront API tokens. These tokens, if exposed, can be a security risk.

Server-Side Handling

Ideally, sensitive operations involving tokens should be handled server-side. This approach ensures that tokens are not exposed to the client side, reducing the risk of unauthorized access.

Scope Control

If you choose to use tokens on the client side, ensure that their scope is limited to accessing only public data. This minimizes the potential damage in case of token exposure.

Conclusion

Integrating GraphQL queries into Shopify Liquid themes requires a creative approach.

By leveraging AJAX and jQuery, developers can fetch data from the Shopify Storefront API and dynamically integrate it into their themes.

This method opens up new possibilities for your Shopify store by integrating GraphQL queries.

For businesses seeking more customized Shopify solutions or ongoing support,  Hopiant offers comprehensive Shopify development services tailored to your specific needs.

Maximize Success For Your Shopify Store With Our Free , Comprehensive Store Audit.

Please enable JavaScript in your browser to complete this form.

Hi, Yogesh Here

Are you running a digital agency? Let’s chat! Our special White Label Services are here to tackle your workload worries and help your agency soar to new heights. Let’s explore how we can grow your business together.
Days :
Hours :
Minutes :
Seconds

— Are you running an agency —

We have special offer for you

Please enable JavaScript in your browser to complete this form.