Search code examples
javascriptpostrequestxmlhttprequest

XMLHttpRequest function return data only in the last call


my problem is...

I made a javascript function to using XMLHttpRequest get some data from my database, using POST method, if i use this function only one time, this works how i want, but i need to call this function more than 1 time in my project and when i call 2 or more times only last request give me some data, the firsts only show the body of POST method but doesn't return data, so the question is...

How can i make this function works every time i call?

And if you guys can tell me why this is happening now i would be grateful too

I put logs in my function to see what's happening and my body for POST method request is there, every single time, but only last function gets a returned data, other even return something...

My function:

var xhr = new XMLHttpRequest();

function getListOfProducts(id, paramsCat, paramsSubcat, insertCheckout) {
  var params1 = {
    id_categoria: paramsCat,
    id_subcategoria: paramsSubcat,
    slug: "",
  };
  console.log(params1);

  xhr.open("POST", url);
  xhr.onload = function () {
    console.log("Loaded");
    var parse = JSON.parse(xhr.response);
    var products = parse.results;
    console.log(products);
  };
  xhr.send(JSON.stringify(params1));
}

Solution

  • As suggested, You can use fetch. In existing code, Create XMLHttpRequest object every time you call getListOfProducts. Since you have same instance of xhr. So this won't work on the next call.

    function getListOfProducts(id, paramsCat, paramsSubcat, insertCheckout) {
      var xhr = new XMLHttpRequest();
      //... rest of the code
    }
    

    Similar code in fetch:

    function getListOfProducts(id, paramsCat, paramsSubcat, insertCheckout) {
      var params1 = {
        id_categoria: paramsCat,
        id_subcategoria: paramsSubcat,
        slug: "",
      };
      fetch({
        url: url,
        body: JSON.stringify(params1),
        method: "POST",
      })
        .then((res) => res.json())
        .then((res) => {
          var products = res.results;
          console.log(products);
        });
    }