I'm trying to build a Vue module on my shopify site so I created a jSON endpoint for the collections:
{% layout none %}
{% paginate collection.products by settings.pagination_limit %}
{
"results": {{ collection.products | json }}
}
{% endpaginate %}
when I visit that endpoint at /collections/collection-slug?view=json I get a full dump of all the products but when I ajax all I get is the collection object with no nested products.
My ajax:
$.getJSON('/collections/mens-slip-on?view=json', function(response) {
console.log(response);
that.products = response;
});
My result:
Object {collection: Object}
collection:Object
description:(...)
handle:(...)
id:(...)
image:(...)
products_count:(...)
published_at:(...)
title:(...)
updated_at:(...)
My Vue component in full:
new Vue({
el: '#filterable',
data: {
collection: null,
products: null
},
mounted() {
this.initCollection();
this.fetchProducts();
},
methods: {
initCollection: function() {
var currPath = window.location.pathname;
this.collection = currPath.substring(currPath.lastIndexOf('/') + 1);
},
fetchProducts: function() {
var that = this;
$.getJSON('/collections/mens-slip-on?view=json', function(response) {
console.log(response);
that.products = response;
});
}
}
});
Vue.config.devtools = true;
It appears that no matter what I put in my collection.json.liquid template it always returns the collection object.
UPDATE: I was able to solve this by using XHR instead of jQuery to do the ajax call. It appears the issue is somehow related to jQuery getJSON but I'm not clear on the reason for this.
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', '/collections/' + this.collection + '?view=json', true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send();
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
parent.products = response.results;
}
}
}
I believe your call is incorrect.
Should be something more like
$.getJSON('/collections/mens-slip-on.json', function(response) {
console.log(response);
that.products = response;
});
That will return the collection object in json format. If you want all the products you would need
$.getJSON('/collections/mens-slip-on/products.json', function(response) {
console.log(response);
that.products = response;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With