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.

Add comment

E-mail is already registered on the site. Please use the Login form or enter another.

You entered an incorrect username or password

Sorry, you must be logged in to post a comment.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for subscribing.

Something went wrong.

Done