Okay so basically I want to have a bit of javascript on a page that somehow attaches some kind of global event listener that can detect and do something if an ajax request is made (without directly calling it from the call), regardless of how the ajax call is made.
I figured out how to do this with jquery - if the ajax request is being done by jquery. Here is an example code for this:
$.post(
// requested script
'someScript.php',
// data to send
{
'foo' : 'bar',
'a' : 'b'
},
// receive response
function(response){
// do something
}
); // .post
// global event listener
$(document).ajaxSend(
function(event,request,settings){
alert(settings.url); // output: "someScript.php"
alert(settings.data); // output: "foo=bar&a=b"
}
);
With this code, regardless of where/how I call $.post(..), the global event listener will trigger. It also works if I use $.get or $.ajax (any jquery ajax methods), regardless of how/when I call it (attached as an onclick, on page load, whatever).
However, I want to be able to extend this listener to trigger regardless of what js framework is used, or even if no framework is used. So for instance if I were to also have on a page the following code (generic ajax code from w3schools):
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.txt",true);
xmlhttp.send();
}
And then I have on some random link an onclick call to that function, my global ajax event listener should be able to also detect this request. Well I added that code to my page and attached it to a random link's onclick (yes, the code itself works), but the jquery "global event listener" code above failed to detect that call.
I did some more digging and I know I can basically save the object to a temp object and overwrite the current object with a "wrapper" object that will call a specified function and then call the temp function, but this requires me to know ahead of time the original object being created/used. But I won't always know that ahead of time...
So...is this possible? Is there some way to detect an ajax get/post request was made, regardless of whether it was done with a generic object or from xyz framework? Or am I just going to have to make duplicate code to handle each framework and also know ahead of time the ajax object(s) being created/used?
edit:
I forgot to mention that it is not enough to detect that a request occurred. I also need to capture the data being sent in the request. The link provided in the comments below will help figure out if "a" request was made, but not get the data sent. p.s. - the answer provided in the link below is not very clear, at least to me anyways.