Home > Enterprise >  Ajax Request Div Without Page Reload
Ajax Request Div Without Page Reload

Time:10-24

I have this <div> element that changes randomly. Sometimes, for example, it is like this:

<td  title="disable"></td>

And sometimes it is like this:

<td  title="Enable"></td>

Can I do an Ajax request every 15 minutes, for example, to alert me if the element changes without reloading the whole page?

This is what I tried:

  $.ajax({
     type: 'POST',
     data: 'gofor="Enabled activeClass',    
     url: 'ajax.php',
     success: function(response) {  
        ClassName("Enabled activeClass").html(response);
     }
  });

I'm kinda new to this stuff so take it easy on me.

CodePudding user response:

I'm assuming this is the problem you are trying to solve:

  • You want a way to be able to know and react to a change to an element on your page.

And you are asking:

  • Can I make an Ajax request from a page, to observe if an element on that same page has changed.

If that is correct, then the answer to your question is No.

Ajax request is for backend calls. You cannot make an Ajax call to fetch the page that the Ajax call is being called from, and get it to observe changes to it. Your Ajax request may be able to fetch the same page, but it will be a fresh copy of that page from your server, and not the instance of the page that the browser is currently displaying.

Instead, to observe changes to specific elements of the DOM (current page) and be able to react to that change, you need to use a MutationObserver. It does exactly what its name says: observe a change to a DOM element.

In order to do that:

  • Define the target of the MutationObserver
const targetNode = document.querySelector('div.active');
  • Define the options for the MutationObserver. This describes what the observer should observe. In this case, we want to
const observerOptions = {
  // Observe only the "class" attribute
  attributeFilter: ['class'],
  // Record the previous value of the "class" attribute 
  // so we can show on the console log
  attributeOldValue: true,
  // Observe only the target node 
  // and ignore changes to children nodes of the target node.
  subtree: false
}
  • Create the callback function for the MutationObserver. This function is called by the observer when it observes a change to the target.
function mutationCallback(mutationList, observer) {
   // TODO: Implement this
}
  • Create the MutationObserver, passing the callback function.
const observer = new MutationObserver(mutationCallback);
  • Start observing, passing the target and the options.
observer.observe(targetNode, observerOptions);
  • At some point when you want to stop the observing changes to the target, you can disconnect the observer.
observer.disconnect();

EXAMPLE

Below is an example where a div is being updated when you click a button. When the button is clicked, it calls toggleDiv() which changes the div's class and title attributes, and the text inside the div.

Then I created a MutationObserver to independently check for changes to the class attribute of the div. This observer only observes class attribute changes on the div. Upon observing a change, it calls the callback function mutationCallback().

function toggleDiv() {
  const el = document.querySelector('div.active');
  const isDisabled = el.classList.contains('disabled');
  if (isDisabled) {
    el.classList.replace('disabled', 'enabled');
    el.setAttribute('title', 'enabled');
    el.innerText = 'Enabled';
  } else {
    el.classList.replace('enabled', 'disabled');
    el.setAttribute('title', 'disabled');
    el.innerText = 'Disabled';
  }
}

function mutationCallback(mutationList, observer) {
  mutationList.forEach((mutation) => {
    if (mutation.type === 'attributes') {
      console.log(`The ${mutation.attributeName} attribute has changed from '${mutation.oldValue}' to '${mutation.target.classList}'`);
    }
  });
}

const targetNode = document.querySelector('div.active');
const observerOptions = {
  // Observe only the "class" attribute
  attributeFilter: ['class'],
  // Record the previous value of the "class" attribute
  attributeOldValue: true,
  // Observe only the target node. Ignore changes to children nodes of the target node.
  subtree: false
}

const observer = new MutationObserver(mutationCallback);
observer.observe(targetNode, observerOptions);
<div  title="disabled">Disabled</div>
<br/>
<button onclick="toggleDiv()">Toggle div</button>

  • Related