I am looking to retrieve data from a product.json file that contains two objects:
- (1) object for CCTV camera products
- (2) object for Laptop products.
When a specific button is clicked, I want to access the data for LAPTOP products and the same for CCTV.
However, a problem arises as AJAX is returning both objects simultaneously. I have tried applying conditions, but I only want to retrieve one object at a time.
//retrieve CCTV camera products
const fetchdata = document.getElementById("fetchNetworkProducts");
fetchdata.onclick = fetchproducts("CCTV");
//retrieve laptop products
const fetchLaptopData = document.getElementById("fetchlaptop");
fetchLaptopData.onclick = fetchproducts("Laptop");
function fetchproducts(product) {//identifying which click event occur
var xhr = new XMLHttpRequest();
xhr.open("get", "/jsondata/Products.json", true);
xhr.onload = function (event) {
event.preventDefault();
console.log();
var obj = JSON.parse(this.responseText);
if (this.status === 200) {
if (product === "CCTV") {
fillProducts(obj.CCTV);
} else if (product === "Laptop") {
fillProducts(obj.Laptop);
}
} else {
console.log("some_error_occur");
}
};
xhr.send();
}