Old post, but still relevant. I had come up with a jQuery AJAX function to obtain product info from a SKU, as well as pull other additional info:
function getProductInfo(productID) {
console.log("Getting product info for " + productID + "...");
$.ajax({
url: window.Shopify.routes.root + 'admin/products/search.json?query=sku:' + productID,
method: "GET",
success: function (data) {
let pid = data.products['0'].id;
let pdpUrl = window.Shopify.routes.root + 'products/' + data.products['0'].handle;
let imgid = data.products['0'].image.src;
let quantity = data.products['0'].variants['0'].inventory_quantity;
if (quantity == 0) {
$('form[data-pid=' + productID + '] button[type=submit]').text('OUT OF STOCK').attr('onclick', 'event.preventDefault();').css("background-color", "#c6c6c6");;
console.log("PRODUCT SOLD OUT: " + productID)
}
$('a[data-sku=' + productID + '] img').css('background-image', "url('" + imgid + "')");
$('a[data-sku=' + productID + ']').attr('href', pdpUrl);
$('form input[value=' + productID + ']').attr('value', pid);
return;
},
error: function (error) {
console.log('Cannot retrieve data from SKU ' + sku);
}
});
};
I also left in some of the success actions to give you guys a good starting point if you wish to build on manipulating the DOM after the function runs. Just a note, this will obtain the parent ID of the product, if you wish to get the product variant ID, you would have to just change this:
let pid = data.products['0'].id;
To this:
let pid = data.products['0'].variants['0'].id;
NOTE: If there is no variant associated with the product, it will throw an undefined error.