I’ve been trying to create an AJAX function for my custom WordPress theme. It’s supposed to fetch data of a custom post type and display it on a sidebar that pops up. I’ve separated the files; functions.php, main.js, sidebar.php. I just can’t seem to figure out why I’m getting a bad request 400 response. This is the code in the function.php
function add_scripts_styles($hook) {
wp_enqueue_script('my_js_file', get_template_directory_uri(). '/assets/js/main.js', array('jquery'), 1);
wp_localize_script('my_js_file', 'ajax_details', array(
'ajax_url' => admin_url('admin.ajax.php'),
'nonce' => wp_create_nonce('my_nonce'),
));
}
add_action("wp_enqueue_scripts","add_scripts_styles");
function do_this(){
$post_id = intval($_POST['post_id']);
ob_start();
echo "Hello World";
$out = ob_get_clean();
$out = strtolower($out);
var_dump($out);
}
add_action("wp_ajax_do_this","do_this");
add_action("wp_ajax_nopriv_do_this","do_this");
this the code in main.js
document.addEventListener('DOMContentLoaded', () => {
const cards = document.querySelectorAll('[id^=tagged]');
function open(){
document.querySelector('.sidebar').style.width = "25%";
}
function close(){
document.querySelector('.sidebar').style.width = "0";
}
cards.forEach(card => {
card.addEventListener('click', e => {
open();
var id_post = e.currentTarget.getAttribute('data-post_ID');
console.log(id_post);
jQuery.ajax({
type: "post",
url: `${window.location.origin}/wp-admin/admin-ajax.php`,
data:{
action: "my_action",
post_id: id_post,
},
success: function(result) {
$('#pusha').html(result.data.html);
}
});
})
})
close();
})
and in sidebar.php
<?php
/*
Sidebar
*/
?>
<div class="sidebar">
<button id="closed"><i class="fa fa-window-close" style="background-color: whitesmoke; color: black"></i></button>
<div id="pusha">
</div>
<script>
let cBtn =document.getElementById('closed');
cBtn.addEventListener('click', e=> {
document.querySelector('.sidebar').style.width = "0";
})
</script>
</div>
I expected to display the post data when the sidebar appears