javascript - How can in get an array of Shopify product ids to return a correct response in GraphQl
I am trying to get a correct response from a graphQl query of an array of products. My goal is to take this array of products and sort it from news to oldest published date. I have tested it with a simple array of two product gids but i am receiving an error response.
Parse error on "gid://shopify/Product/777229615129" (STRING) at [1, 16]
here is my code:
const token = 'Storefront API custom app token';
const queryPage = JSON.stringify({
query:`query ($ids : ["gid:\/\/shopify\/Product\/777229615129","gid:\/\/shopify\/Product\/7772297068794"]) {
nodes(ids:$ids){
... on Product{
id
title
}
}
}`
});
const storefrontSettingsPage = {
"async": true,
"crossDomain": true,
"url": "https://"+shopname+".myshopify.com/api/2022-07/graphql.json",
"method": "POST",
"headers": {
"X-Shopify-Storefront-Access-Token": token,
"Content-Type": "application/json"
},
"data": queryPage,
};
$.ajax(storefrontSettingsPage).done(function (response) {
console.log(response);
});
I am still learning to use graphQl, what am I doing wrong.
Thank you for your support.
Answer
Solution:
Still not one hundred percent sure on how it works, but was able to makes this work using a different type of writing style, and using variables.
const token = 'Storefront API custom app token';
$.ajax({
url: "https://"+shopname+".myshopify.com/api/2022-07/graphql.json",
contentType: "application/json",
type:'POST',
headers:{
"X-Shopify-Storefront-Access-Token": token,
"Content-Type": "application/json"
},
data: JSON.stringify({
query:`query ($ids : [ID!]!) {
nodes(ids:$ids){
... on Product{
id
title
}
}
}`,
variables: {
ids:["gid://shopify/Product/7772296151290","gid://shopify/Product/7772297068794"]
}
}),
}).done(function (response) {
console.log(response);
});
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.