Home > Net >  How to get a specific element from a page to another using JS and Ajax?
How to get a specific element from a page to another using JS and Ajax?

Time:12-09

I need to build a script (fully JS, no jQuery allowed) that will perform some actions on a page, let's call it the Active page, based on data that are stored on a different page (same domain), call it the Passive page.

These data are stored in specific HTML elements in the Passive page.

I'm totally new to Ajax, so before starting out I tried to make research on the internet, but found nothing useful (or, maybe, nothing I could understand).

How can I retrieve the specific data I need?

I'm stuck with this little code, which however only returned me the page 'skeleton':

javascript:

var myAttempt = new XMLHttpRequest();
myAttempt.onreadystatechange = function() {
 if (this.readyState == 4 && this.status == 200) {
    myAttempt = this.responseText;
 }
}
myAttempt.open("GET", "https://www.website.com/passivepage.html", true);
myAttempt.send();

Where should I tell the script to look for a specific element of the Passive page?

Thanks

CodePudding user response:

With your ajax request you receive a string as response, to find an specific element inside it you can create a dummy DOM element and add the string to it, then find every element you are looking for inside dummy element. like this:

var myAttempt = new XMLHttpRequest();
myAttempt.onreadystatechange = function() {
 if (this.readyState == 4 && this.status == 200) {
    var div = document.createElement('div');
    div.style.display = 'none';
    div.innerHTML = this.responseText;
    document.body.append(div);
    const theElement = div.querySelector('selector');
    alert(theElement.getAttribute('x'));
 }
}
myAttempt.open("GET", "/url", true);
myAttempt.send();
  • Related