JavaScript Detect an Ajax Event

JavaScript: Detect AJAX requests

Here's some code (tested by pasting into Chrome 31.0.1650.63's console) for catching and logging or otherwise processing ajax requests and their responses:

(function() {
var proxied = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
console.log( arguments );
//Here is where you can add any code to process the request.
//If you want to pass the Ajax request object, pass the 'pointer' below
var pointer = this
var intervalId = window.setInterval(function(){
if(pointer.readyState != 4){
return;
}
console.log( pointer.responseText );
//Here is where you can add any code to process the response.
//If you want to pass the Ajax request object, pass the 'pointer' below
clearInterval(intervalId);

}, 1);//I found a delay of 1 to be sufficient, modify it as you need.
return proxied.apply(this, [].slice.call(arguments));
};

})();

This code solves the above issue with the accepted answer:

Note that it may not work if you use frameworks (like jQuery), because
they may override onreadystatechange after calling send (I think
jQuery does). Or they can override send method (but this is unlikely).
So it is a partial solution.

Because it does not rely on the 'onreadystatechange' callback being un-changed, but monitors the 'readyState' itself.

I adapted the answer from here: https://stackoverflow.com/a/7778218/1153227

JavaScript detect an AJAX event

Okay this is what I have come up with so far:

<script type='text/javascript'>
var s_ajaxListener = new Object();
s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
s_ajaxListener.callback = function () {
// this.method :the ajax method used
// this.url :the url of the requested script (including query string, if any) (urlencoded)
// this.data :the data sent, if any ex: foo=bar&a=b (urlencoded)
}

XMLHttpRequest.prototype.open = function(a,b) {
if (!a) var a='';
if (!b) var b='';
s_ajaxListener.tempOpen.apply(this, arguments);
s_ajaxListener.method = a;
s_ajaxListener.url = b;
if (a.toLowerCase() == 'get') {
s_ajaxListener.data = b.split('?');
s_ajaxListener.data = s_ajaxListener.data[1];
}
}

XMLHttpRequest.prototype.send = function(a,b) {
if (!a) var a='';
if (!b) var b='';
s_ajaxListener.tempSend.apply(this, arguments);
if(s_ajaxListener.method.toLowerCase() == 'post')s_ajaxListener.data = a;
s_ajaxListener.callback();
}
</script>

DIRECTIONS:

Just c/p this onto your page or include it in a .js file or whatever. This will create an object called s_ajaxListener. Whenever an AJAX GET or POST request is made, s_ajaxListener.callback() is called, and the following properties are available:

s_ajaxListener.method : The ajax method used. This should be either GET or POST. NOTE: the value may not always be uppercase, it depends on how the specific request was coded. I'm debating the wisdom of automatically upper-casing it or leaving it to something else to toLowerCase() for a case-insensitive comparison.

s_ajaxListener.url : The url of the requested script (including query string, if any) (urlencoded). I have noticed, depending on how the data is sent and from which browser/framework, for example this value could end up being as " " or "+" or "%20". I am debating the wisdom of decoding it here or leave it to something else.

s_ajaxListener.data : the data sent, if any ex: foo=bar&a=b (same 'issue' as .url with it being url-encoded)

NOTES:

As it stands, this is not IE6 compatible. this solution is not quite good enough for me, as I want it to be IE6 compatible. But since a lot of other people don't care about IE6, I decided to post my solution in its current state, as it should work for you if you don't care about IE6.

I have tested this in (as of this posted date): Current Safari, Current Chrome, Current FireFox, IE8, IE8 (IE7 Compatible). It doesn't currently work with IE6 because IE6 uses an ActiveX object, while virtually everything else uses XMLHttpRequest.

Right now I don't have any clue how to, well basically prototype/extend/overload (?) ActiveXObject("Microsoft.XMLHTTP"). This is what I am currently researching...does anybody know offhand?

Under each of the browsers I tested above, this works with AJAX requests from a generic object, and also from the jquery and prototype frameworks. I know there are other frameworks out there, but IMO these 2 are the major ones. I might possibly QA MooTools, but other than that, I'm fine with only testing those.

If Anybody wants to contribute by testing and posting results about other browsers and/or frameworks, it would be appreciated :)

detect ajax request by jquery

well, if $(document).ajaxStart(function() {}); is not working for you,
try a bit raw js,

var oldXHR = window.XMLHttpRequest;

function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
if(realXHR.readyState==1){
alert('server connection established');
}
if(realXHR.readyState==2){
alert('request received');
}
if(realXHR.readyState==3){
alert('processing request');
}
if(realXHR.readyState==4){
alert('request finished and response is ready');
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;

it should give you all the states of a ajax request and check which one works for you, and then u can remove rest of the if conditions. you can place it outside of $(document).ready(function(){});

Monitoring all AJAX requests made by JQuery on WooCommerce

You can use:

  • ajaxSend() that attach a function to be executed before an Ajax request is sent,
  • ajaxComplete() that register a handler to be called when Ajax requests complete.

Both gives details related to the Ajax event that is triggered on a readable XHR Object in your browser Javascript console.

Here is a code example, that displays Ajax triggered request details:

add_action( 'wp_footer', 'monitor_jquery_ajax_requests' );
function monitor_jquery_ajax_requests() {
?>
<script>
jQuery(document).ajaxSend( function( event, xhr, options ) {
console.log('------- ' + event.type + ' -------');
console.log(xhr);
console.log('------------------------');
}).ajaxComplete( function( event, xhr, options ) {
console.log('----- ' + event.type + ' -----');
console.log(xhr);
console.log('----------------------------');
});
</script>
<?php
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

After checkout page load for example you will get something like:

Sample Image

Sample Image

Related: Monitoring all AJAX requests made by JQuery?

How to detect change of select from ajax loaded content

The two usual ways to do this are:

  1. Call .change() with an appropriate selector after adding the elements to the page (from in your Ajax success handler, or wherever).

  2. Setup a delegated event handler attached to a parent or ancestor element that does exist at page load (document, if there is no closer ancestor).

Here's how to create a delegated handler using the .on() method:

$("#idOfAncestorThatExistsOnLoad").on("change", "selectorOfDynamicElements", function() {
// do something here
});

When the change event bubbles up to the ancestor element jQuery automatically tests whether it originated with an element matching the selector in the second parameter, and only calls the handler function if it does match.

Detect a click on a div that's inside an Ajax call

You need to use .on() and delegate the events.

 $.ajax({ ...
success: function(data){

//add to favorite function - THIS CLICK HANDLER KEEPS DUPLICATING

},

$(document).on("click", '.favit', function(){
var cid=$(this).data("id");
addfav(cid); //execute function
return false;
});

How can I detect 'any' ajax request being completed using jQuery?

Unfortunately this doesn't apply since it seems the OP isn't using $.ajax() or any jQuery ajax method for actually loading content, but leaving it here in case future googler's are doing this.


You can use any of the global ajax events that meet your needs here, you're probably after $.ajaxComplete() or $.ajaxSuccess().

For example:

$(document).ajaxSuccess(function() {
alert("An individual AJAX call has completed successfully");
});
//or...
$(document).ajaxComplete(function() {
alert("ALL current AJAX calls have completed");
});

If you want to run just some generic function then attach them to document (they're just events underneath). If you want to show something in particular, for example a modal or message, you can use them a bit neater (though this doesn't seem to be what you're after), like this:

$("#myModal").ajaxComplete(function() {
$(this).fadeIn().delay(1000).fadeOut();
});


Related Topics



Leave a reply



Submit