I'm trying to do an ajax request from my themes header.php
file. I've read that I have to use the admin-ajax.php
file to achieve this. So I looked for examples and found this one.
My code in the header.php
file looks like this:
<script>
$(document).ready(function(){
$('.test a').click(function(){
var className = $(this).attr('class');
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
'action': 'myFunc',
'id': className
},
success: function(res){
alert(res);
},
error: function(err){
alert("Error: " + err);
}
});
});
});
</script>
And my PHP code looks like this:
function myFunc() {
echo "hello";
die();
}
add_action('wp_ajax_nopriv_myFunc', 'myFunc');
I'm not sure where I should put this PHP code. Should I put this in my functions.php
file or directly to the admin-ajax.php
file? It doesn't matter where I put the PHP code, the output is always 0 (the last line in admin-ajax.php
is die('0')
). Or is it because of my url
parameter?
nopriv
and without. Both of them doesn't work.