Is Ajax capable of producing multiple outputs at once?

I am looking to retrieve data from a product.json file that contains two objects:

  1. (1) object for CCTV camera products
  2. (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();
}

Answer №1

When you invoke your function like this :

fetchproducts("Laptop");
the returned value from the function is assigned to fetchLaptopData.onclick which is then automatically triggered. See the following demo code for illustration:

//for fetching CCtv camera products                                                                                             
const fetchdata = document.getElementById("fetchNetworkProducts");
fetchdata.onclick = fetchproducts("CCTV");
//for fetching laptop products
const fetchLaptopData = document.getElementById("fetchlaptop");
fetchLaptopData.onclick = fetchproducts("Laptop");

function fetchproducts(product) { //identifying the click event
  console.log(product);
  //your ajax code..

}
<button id="fetchNetworkProducts">Abc</button>
<button id="fetchlaptop">Abc</button>

Instead, use the following pattern to call your function :

//for fetching CCtv camera products                                                                                         
document.getElementById('fetchNetworkProducts').onclick = function() { //call function
  fetchproducts('CCTV');
}

document.getElementById('fetchlaptop').onclick = function() {
  fetchproducts('Laptop');
}

function fetchproducts(product) { //identifying the click event
  console.log(product);
 //your ajax code..

}
<button id="fetchNetworkProducts">Abc</button>
<button id="fetchlaptop">Abc</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Is there a variance in window.innerWidth between Chrome and Firefox?

body, html { position:absolute; width:100%; height:100%; margin: 0; padding: 0; overflow: hidden; } When using window.innerWidth, there is a discrepancy between the values returned by Firefox and Chrome. Firefox return ...

Retrieve all elements from JSON using jQuery

JavaScript: function loadDoc(url) { $.ajax({ url: 'mytestjson', dataType: 'json', cache: false }).success(function (result) { console.log(result); //var txt = result.newBranches[0].newNon ...

Executing a Python script in Django and transferring its output to a JavaScript file

Getting Started with Django What I'm Looking For: 1 - Execute a Python Script 2 - Pass data to a JavaScript file I'm unsure if the sentence I've constructed is technically accurate in terms of Django. Below are the JavaScript and Python ...

Having trouble adjusting the label fontSize in ReactJS when using semantic-ui-react?

Is there a way to decrease the size of the label for a form input? In this scenario, attempting to set the fontSize does not work: <Form.Input label="Username" style={{fontSize: '10px'}} /> Does anyone have any suggestions on how to res ...

Sending information from JavaScript to Python scripts: best practices

Within this HTML file, I have included a script where an ajax request is being made to pass a specific string to a Python function. var message = "hello there!!!" $.ajax({ url: "../SCRIPTS/cond.py", type: 'POST', ...

Steer clear of using the onRowClick event if an outputLink is clicked within a RichFaces datatable

What is the best way to prevent the call to onRowClick on a column with an output link in a datatable that targets a new window? <rich:dataTable id="dt" value="#{bean.cars} var="_car"> <a:support event="onRowCli ...

Having trouble accessing the scrollHeight property of null when using Selenium WebDriver

I am currently working on a function in my code that is responsible for scrolling the page. This particular function was inspired by code used to scrape Google Jobs, which can be found here. However, I encountered an error that reads "javascript error: Ca ...

Concatenate a variable string with the JSON object key

I am currently working on a request with a JSON Object structure similar to the following: let formData = { name: classifierName, fire_positive_examples: { value: decodedPositiveExample, options: { filename: 'posit ...

Trouble loading JSON files

I am currently encountering an issue and would greatly appreciate some guidance or best practices. My Titanium SDK version is 1.6.1 and my iPhone SDK version is 4.2. My application performs the following task: it retrieves a remote JSON file to sync with ...

Having issues sorting the ranking table numerically in a Javascript/jQuery/JSON/localStorage game

I have successfully created a leaderboard for my game, but I am struggling to automatically sort the scores from high to low. I believe that placing the objects into an array and then sorting them may be the solution, however, I am unsure of how to do th ...

Is it possible to extract the selected indexes of all select menus in my HTML and assign them to various arrays of my choosing? I find myself writing a lot of code just for one select menu

In order to determine which TV character the user most closely resembles based on their answers to a series of questions, I have created a function. However, my current code is inefficient when it comes to handling multiple select menus! I am considering i ...

Turn off automatic zooming for mobile device input

One common issue observed in mobile browsers is that they tend to zoom in on an input field or select drop-down when focused. After exploring various solutions, the most elegant one I came across involves setting the font-size of the input field to 16px. W ...

Using jQuery to fetch and display content only when the user hovers over

Looking to optimize page loading speed by minimizing the loading time of social icons such as Facebook Like and Twitter follow buttons. Considering displaying a static image of the like buttons initially, with the actual buttons appearing on mouse hover. ...

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...

What is the process to obtain the child theme URL in WordPress?

Currently, I am working on creating a child theme for my WordPress website. I have successfully uploaded the assets folder which contains both CSS and JavaScript files. This child theme will be completely customized to suit my needs. Within the <head&g ...

Tips on executing a $.get request while submitting a form?

Instead of using AJAX to submit my form, I am trying to implement a progress bar by making GET requests to the server while the form is submitting. This is particularly important when dealing with multiple file uploads that may cause the submission to take ...

Should the header include individual CSS and JS files, or should all code be contained within a single CSS and JS file?

As I work on optimizing my website, I find myself juggling multiple plugins that include jQuery plugins with CSS along with my own JavaScript code. Currently, the CSS is spread across separate files for each plugin I have downloaded. When needed on a page ...

What is the best way to assess a scope object within an ng-Class directive?

Whenever I click a button, it moves to the next item in an array. Once it reaches the last item in the array, I want to assign the "endButton" class to the button tag. I plan to use the ng-class directive within the HTML code to evaluate the expression. T ...

Interacting with jQuery UI Droppable by setting acceptance criteria before submitting a form

My goal is to create a draggable item that can be dropped onto a specific zone. The challenge I'm facing is in displaying a form for inputting information and storing it in a database. If the input is successfully stored, the drop action will be succe ...