I've searched the forums for this but I'm not sure where to start with this.
I was wondering if it's possible to create a reusable $.getJSON or $.each() function to create product html. To clarify, I'm creating a site which has multiple getjson functions actually doing the same work over and over again.
So function a() does a json request and with that data it creates some product html. Function b() does a json request to a different location but creates the same product html.
I'm just trying to write with less code :)
To give an example:
function abc() {
$.getJSON(url-to-a, function(data) {
var products = [];
$.each(data.bundle.products, function(index, product) {
var productHtml = '<div class="item">'+ product.title + '</div>'
products.push(productHtml);
});
products.join('');
container.html(products);
});
}
function xyz() {
$.getJSON(url-to-different-location, function(data) {
var products = [];
$.each(data.search.products, function(index, product) {
var productHtml = '<div class="item">'+ product.title + '</div>'
products.push(productHtml);
});
products.join('');
container.html(products);
});
}
As you can see it are different functions but mostly doing the same work. Especially in the $.each() function.
What I was wondering if it's possible to create something like this:
function createProductContentForAllFunctions(url, getThisData, container){
return $.get(url, function(data){
var products = [];
$.each(getThisData, function(i, product) {
var productHtml = '<div class="item">'+ product.title + '</div>'
products.push(productHtml);
});
products.join('');
container.html(products);
});
}
and then call the function something like:
function abc() {
createProductContentForAllFunctions('url-to-a', data.bundle.products, '.bundle')
}
function xyz() {
createProductContentForAllFunctions('url-to-different-location', data.search.products, '.search')
}
To be honoust I'm not sure where to start :) If I use the code in my example, so createProductContentForAllFunctions('url-to-different-location', data.search.products, '.search') I get errors like uncaught TypeError: cannot use 'in' operator to search for "length" in "product"
So my question is if it's even possible? Is it worth trying? And where should I start?
data.bundle.productsanddata.search.productsis nothing when running the getJSON function. It gives the erroruncaught TypeError: cannot use 'in' operator to search for "length" in "product"...