Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  92] [ 5]  / answers: 1 / hits: 25655  / 14 Years ago, fri, december 10, 2010, 12:00:00

I need to build a feature into a shopping cart that uses AJAX to retrieve an updated copy of the template from the server when something changes (e.g. a product is removed). I cannot modify the server side code, or the JavaScript that makes the shopping cart work in the first place. (Not ideal I know, but that's how it is)



What I want to do is run my own JavaScript every time the cart updates. I want to know if it is possible to listen for AJAX calls, and run my code every time one is made.


More From » jquery

 Answers
29

To follow all AJAX calls on an HTML doc, you can overwrite the XMLHttpRequest prototype.
This way, you can watch for actions on methods of XMLHttpRequest objects.



Here's a small sample code :



var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send,
onReadyStateChange;

function openReplacement(method, url, async, user, password) {
var syncMode = async !== false ? 'async' : 'sync';
console.warn(
'Preparing ' +
syncMode +
' HTTP request : ' +
method +
' ' +
url
);
return open.apply(this, arguments);
}

function sendReplacement(data) {
console.warn('Sending HTTP request data : ', data);

if(this.onreadystatechange) {
this._onreadystatechange = this.onreadystatechange;
}
this.onreadystatechange = onReadyStateChangeReplacement;

return send.apply(this, arguments);
}

function onReadyStateChangeReplacement() {
console.warn('HTTP request ready state changed : ' + this.readyState);
if(this._onreadystatechange) {
return this._onreadystatechange.apply(this, arguments);
}
}

window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;


With this sample, for every AJAX call you'll have a warning in the JavaScript console.



It's not jQuery script, but you can use jQuery inside as you want.



This solution probably won't work on IE 6 or older, but it works in FF, IE7+, Chrome, Opera, Safari...


[#94653] Wednesday, December 8, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andreguym

Total Points: 125
Total Questions: 112
Total Answers: 103

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;