I am trying to use an ajax request on page unload/visibilityChange. I found navigator.sendBeacon
is a best option for that. I tried using it with WordPress, the request is being sent but I get 'POST 400 bad request' error.
Here is my js code:
let array_data_on_unload = [url1, url2, url3]; //array of urls
let unload_delete_data = {
action: 'delete_on_unload',
source_urls: JSON.stringify(array_data_on_unload)
};
if(array_data_on_unload.length >= 1){
let result = navigator.sendBeacon(window.location.protocol+'//'+window.location.hostname+'/wp-admin/admin-ajax.php', unload_delete_data);
console.log(result); //returns true in console
}
My php code in functions.php
add_action( 'wp_ajax_delete_on_unload', 'delete_on_unload' );
add_action( 'wp_ajax_nopriv_delete_on_unload', 'delete_on_unload' );
function delete_on_unload(){
$response = array('success' => true);
$file_urls = json_decode(stripslashes($_POST['source_urls']));
foreach($file_urls as $file_url){
//do the delete operation
}
exit(json_encode($response));
}
Why is this returning POST [domain]/wp-admin/admin-ajax.php 400 (Bad Request)
error?
I figured out. we can't change header in
sendBeacon
. So for it to send the data as json object. we can send it as formData();. see below code