How should i create two object to do two different ajax calls?

I have:

var xhr = new XMLHttpRequest();                 

xhr.onload = function() {                    
  
  if(xhr.status === 200) {                     
    document.getElementById('content').innerHTML = xhr.responseText; // Update
  }
};

xhr.open('GET', 'data/data-one.html', true);        // Prepare the request
xhr.send(null);

Now i want to do the same thing for another link, so when the link is clicked, in the code above, data-one.html is inserted to the html container with an id of content in my html page. now lets image i have another link in my nav and want to do the same process for another html container with an id of content1 this time to insert data-two.html . do i have to create the httprequest in this file or another ajax file? are the variables gonna be different? cuz i already tried with the same variable both in the same file and other files but i get an error saying the i can’t set the innerHTML to Null. i can’t find out why please help.

Hey,

Try specifying the name of the file that you want to get and the name of the container to insert it into as a data attributes on the link that your visitors click.

E.g.

<a href="#" data-page="data/data-one.html" data-container="content">One</a>
<a href="#" data-page="data/data-two.html" data-container="content">Two</a>

and:

var links = document.querySelectorAll("a");
[].forEach.call(links, function (link) {
    link.addEventListener('click', function(e) {
      e.preventDefault();
      makeAjaxRequest(this.dataset.page, this.dataset.container);
    }
  });
});

finally:

function makeAjaxRequest(page, container){
  var xhr = new XMLHttpRequest();                 

  xhr.onload = function() {                    
    if(xhr.status === 200) {                     
      document.getElementById(container).innerHTML = xhr.responseText;
    }
  };

  xhr.open('GET', page, true); 
  xhr.send(null);
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.