How to Detect Ajax Request using Javascript

I was working on a script to get the engagement data such as reaction, comments, and shares of a specific URL using Facebook Javascript SDK. I was able to get the data without issues using the following snippet structure.

(function($){
   window.fbAsyncInit = function() {   
      FB.init({
         appId : 'APP_ID',
         autoLogAppEvents : true,
         xfbml : true,
         version : 'v2.11'
      });
      
      // Some code to make the API call here and DOM element injection
   };
})(jQuery);

One built-in feature of the site is the infinite loading of posts when a button is clicked. The request is made via an AJAX call which injects the new set of data into the DOM when the request is completed.

However, there will be an issue on my side because the script that will retrieve the Facebook stats is done on the client side when everything is loaded. So the newly injected set of posts don’t have the stats as it is dynamically injected.

One solution I’ve thought is to detect any AJAX request using Javascript.

The following code is an updated version of above which solves the issue.

(function($){

   window.fbAsyncInit = function() {
   
   FB.init({
      appId : 'APP_ID',
      autoLogAppEvents : true,
      xfbml : true,
   version : 'v2.11'
   });   
   // Some code to make the API call here and DOM element injection   
   };
   
   var proxied = window.XMLHttpRequest.prototype.send;
   window.XMLHttpRequest.prototype.send = function() {
      var pointer = this
      var intervalId = window.setInterval(function(){
         if(pointer.readyState != 4){
            return;
         }
         window.fbAsyncInit();
         clearInterval(intervalId);
      }, 1);
      return proxied.apply(this, [].slice.call(arguments));
   };

})(jQuery);

It does not rely on the ‘onreadystatechange‘ callback being un-changed, but monitors the ‘readyState‘ itself. See XMLHttpRequest.readyState definition.

When the readyState status is DONE, it will run the window.fbAsyncInit(); function again which can now access the newly added elements.

Cromwell Bayon

He is a self-tutored programmer and a Full-Stack Developer. He strives to excel in the newest technology as possible. He has a very high sense of technicality and analytical skills which allows him to resolve any kind of issues related to technology. He also loves woodworking. Read more about him here...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.