I have been struggling these days when passing a data array in WordPress to be processed via admin-ajax.php. I have added a button in the WooCommerce hook 'woocommerce_after_shop_loop_item' that contains a data-product_id with a class of compare-button. My problem is that I am getting a sort of 'many times' stringified array (with escaped quotes, pictures shown). My goal is to pass an array of clicked products Ids to admin-ajax.php and there process this array. I can't do it probably due to the format of the array as string. If I use json_decode I also get an error (while this way it works if tested in localhost not in WordPress environment). If I JSON decode it first and check if an ID is in the array again it is not working. What I am I doing wrong?
function ps_compare_products_add_enqueue(){ wp_enqueue_script('ps_script1', plugin_dir_url(__FILE__).'../script/script.js'); wp_localize_script('ps_script1','ps_object', array( "ajax_url" => admin_url("admin-ajax.php") )); } function process_array_ids(){ if(isset($_POST['my_string_array']) && !empty($_POST['my_string_array'])){ $array = $_POST['my_string_array']; //$array = json_decode($array); // if I add this I get null in my console which in not wordpress environment works echo json_encode($array); // the only way I found to send back the array but in string format again } wp_die(); } add_action('wp_enqueue_scripts','ps_compare_products_add_enqueue'); add_action('wp_ajax_my_array_ids_action', 'process_array_ids'); add_action('wp_ajax_nopriv_my_array_ids_action', 'process_array_ids');
Javascript
document.addEventListener('DOMContentLoaded', function() { let compareProducts = [] var compareButtons = document.querySelectorAll('.compare-button'); document.addEventListener('click', (e) => { if(e.target.matches('.compare-button')){ var productId = e.target.dataset.product_id; if (!compareProducts.includes(productId)) { compareProducts.push(productId); } fetch_my_array(ps_object.ajax_url, 'POST', compareProducts) } }); }) async function fetch_my_array(url, post, myArray){ let myForm = new FormData() let my_string_array = JSON.stringify(myArray) myForm.append('action', 'my_array_ids_action') myForm.append('my_string_array', my_string_array) const options={ method: post, body: myForm } const response = await fetch(url, options) let result = await response.json() console.log(response) console.log(result) // console.log(JSON.parse(result.replaceAll('\\"',''))) }
$_POST['my_string_array']
actually contain, and what didjson_last_error
have to report after your attempt to decode it?json_last_error
after decoding throws number 4 (which is null apparently). Using stripslashes() from the accepted answer below solved the issue. Thanks for your help 🙏