Retrieve product metafields via Ajax API

Retrieve product metafields via Ajax API

tsanstef
Visitor
1 0 0

Dear shopifiers,

 

I have been trying to pull product metafield data via AJAX API with no success. And, no, I cannot use Liquid as the idea is to have the user enter a product and without navigation (without leaving the page and triggering a refresh) to show some additional data on the screen stored in the metafields of a product.

 

I already tried the following standard approach:

var action = '/products/'+$("#id", $("#myform")).val()+'.json'; /*construct the product path using the input field of a form*/
jQuery.getJSON(action,
function(product) {
  console.log(product); /*no metafields in here*/
} );

 

Basically, the above returns everything about the product, but without the metafields. I am still perplex of why Shopify decided to suppress this information as the metafields are key to building custom features. So a key piece of content missing from the AJAX API for inexplicable (to me at least) reasons. The last two sentences were in case someone from Shopify was reading this (I hope you realize the problem this creates and simply add it to the JS product) :).

Does anyone has a solution in mind? Thank you in advance!

Replies 3 (3)

MetafieldsGuru
Shopify Partner
160 32 102

Hi @tsanstef ,

The first thing I noticed is that your request path is missing the "/metafields" part. In order to access metafields, one has to use the following API path:

https://SHOPIFY_STORE_URL/admin/products/PRODUCT_ID/metafields.json

but your code seems to use something like this:

https://SHOPIFY_STORE_URL/admin/products/PRODUCT_ID.json

So you may want to try fixing the request path and see if it helps. Also, you may want to consider using the storefront API to access the metafields. As far as I know, it's a common solution to your problem. Keep in mind that you'll also need to expose metafields to this API to be able to access the data. Hope this helps!

Check out Metafields Guru, the #1 ranked metafields app.

Bulk editor | Data import/export | Metafield sets | Browser extension
electrodrel
Shopify Partner
8 0 2

There is no /admin/ in the code above. It's a unauthorized Ajax API. Basically append 'json' or 'js' to any product url and it will show up, no need for authentication.
And no, adding 'metafields' to the path doesn't make any difference

RichC
Shopify Partner
9 0 13

You could create an alternate product template with {% layout none %} that simply returns a JSON of the metafields you need built with liquid. I haven't tested, but you then request the JSON using something like:

 

fetch(`/products/[PRODUCT ID]?view=[TEMPLATE NAME]`)

 

 The alternate product template could be as simple as:

 

{% layout none %}

{
  "metafield": {{ product.metafields.[NAMESPACE].[KEY].value | json }}
}