I have this <div> element that changes randomly. Sometimes, for example, it is like this:
<td class="Disabled activeClass" title="disable"></td>
And sometimes it is like this:
<td class="Enabled activeClass" 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.
I'm assuming this is the problem you are trying to solve:
And you are asking:
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:
MutationObserverMutationObserver. This describes what the observer should observe. In this case, we want toMutationObserver. This function is called by the observer when it observes a change to the target.MutationObserver, passing the callback function.EXAMPLE
Below is an example where a
divis being updated when you click abutton. When thebuttonis clicked, it callstoggleDiv()which changes thediv's class and title attributes, and the text inside thediv.Then I created a
MutationObserverto independently check for changes to the class attribute of thediv. This observer only observes class attribute changes on thediv. Upon observing a change, it calls the callback functionmutationCallback().