Add a hook to all AJAX requests on a page
Inspired by aviv's answer, I did a little investigating and this is what I came up with.
I'm not sure that it's all that useful as per the comments in the script and of course will only work for browsers using a native XMLHttpRequest object.
I think it will work if javascript libraries are in use as they will use the native object if possible.
function addXMLRequestCallback(callback){
var oldSend, i;
if( XMLHttpRequest.callbacks ) {
// we've already overridden send() so just add the callback
XMLHttpRequest.callbacks.push( callback );
} else {
// create a callback queue
XMLHttpRequest.callbacks = [callback];
// store the native send()
oldSend = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function(){
// process the callback queue
// the xhr instance is passed into each callback but seems pretty useless
// you can't tell what its destination is or call abort() without an error
// so only really good for logging that a request has happened
// I could be wrong, I hope so...
// EDIT: I suppose you could override the onreadystatechange handler though
for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
XMLHttpRequest.callbacks[i]( this );
}
// call the native send()
oldSend.apply(this, arguments);
}
}
}
// e.g.
addXMLRequestCallback( function( xhr ) {
console.log( xhr.responseText ); // (an empty string)
});
addXMLRequestCallback( function( xhr ) {
console.dir( xhr ); // have a look if there is anything useful here
});
Is it possible to listen all Ajax calls?
Try this:
$(document).ajaxStart(function () {
console.log('Request Initiated');
});
$(document).ajaxComplete(function () {
console.log('Request Complete');
});
How to intercept all AJAX requests made by different JS libraries
This type of function hooking is perfectly safe and is done regularly on other methods for other reasons.
And, the only performance impact is really only one extra function call for each .open()
plus whatever code you execute yourself which is probably immaterial when a networking call is involved.
In IE, this won't catch any code that tries to use the ActiveXObject
control method of doing Ajax. Well written code looks first for the XMLHttpRequest
object and uses that if available and that has been available since IE 7. But, there could be some code that uses the ActiveXObject
method if it's available which would be true through much later versions of IE.
In modern browsers, there are other ways to issue Ajax calls such as the fetch()
interface so if one is looking to hook all Ajax calls, you have to hook more than just XMLHttpRequest
.
Ajax request not save form data when add woocommerce hook
I found a solution, we needed to add array with var to the hook &$errors
&$user
add_action( 'woocommerce_save_account_details_errors', array( &$errors, &$user ), 1, 10 );
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
function save_account_details( $user_id ) {
if (trim($_POST['account_first_name']) == '') {
wc_add_notice("<b>Nome</b> è un campo obbligatorio", "error");
$response = wc_print_notices();
} else if ( isset( $_POST['account_first_name'] ) ) {
wc_add_notice("Modifiche salvate con successo", "success");
$response = wc_print_notices();
}
echo json_encode($response);
exit();
}
React Hooks - Making an Ajax request
You could create a custom hook called useFetch
that will implement the useEffect
hook.
If you pass an empty array as the second argument to the useEffect
hook will trigger the request on componentDidMount
. By passing the url
in the array this will trigger this code anytime the url
updates.
Here is a demo in code sandbox.
See code below.
import React, { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
const response = await fetch(url);
const json = await response.json();
setData(json);
}
fetchData();
}, [url]);
return data;
};
const App = () => {
const URL = 'http://www.example.json';
const result = useFetch(URL);
return (
<div>
{JSON.stringify(result)}
</div>
);
}
Related Topics
Difference Between Textcontent VS Innertext
Looping Through an Object (Tree) Recursively
Why Does (0 < 5 < 3) Return True
Removing # from Url in Angularjs While Having .Run in Routes
Keycode on Android Is Always 229
How to Create a Custom Scrollbar on a Div (Facebook Style)
Anchor Jumping by Using JavaScript
Performance Differences Between Visibility:Hidden and Display:None
Enter Key Press Behaves Like a Tab in JavaScript
React-Router - Pass Props to Handler Component
How to Make JavaScript Object Using a Variable String to Define the Class Name
How to Make Post Requests with the Formdata API
\U200B (Zero Width Space) Characters in My Js Code. Where Did They Come From
How to Add and Remove Classes in JavaScript Without Jquery