I am trying to learn how to process AJAX requests in WordPress the correct way. To do this I am adapting this tutorial to create a super simple AJAX request to place the ID of a post (from a link) into my page content.
The Logic
- When the
#our-work a
links are clicked - Get the post ID (from the
data-id
attribute) & store it aspostID
variable - Pass
postID
via an AJAX (using the WP’sadmin-ajax.php
file) - The
example_ajax_request
function will pick up the ID & simply echo it - If successful, append the server response to the
#hero
div.
I realise this has no benefit but once I have that working I will amend the function to serve a real purpose.
My Code
Here is a copy of the function I have created in the plugins folder:
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'acl-plugin.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
function example_ajax_request() {
if ( isset($_REQUEST) ) {
$postID = $_REQUEST['postID'];
echo $postID;
}
die();
}
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
And here is a copy of the JS file
jQuery(document).ready(function($) {
$('#our-work a').click( function() {
var postID = $(this).attr("data-id");
$.ajax({
url: MyAjax.ajaxurl,
data: {
'action':'example_ajax_request',
'postID' : postID
},
success:function(data) {
$('#hero').append( "Well this seems to work" + data );
},
error: function(errorThrown){
console.log("This has thrown an error:" + errorThrown);
}
});
return false;
});
});
The Problem
Upon clicking the link the JS does fire but yields the following response:
<div id="hero">
Well this seems to work 0
</div>
Using an alert I know the ID is being picked up before the AJAX request. So the problem is in my function. To find out more, I (temporarily) tweaked WP’s admin-ajax.php
file, so that I could find out which die();
was yielding the response of “0”.
It is the very last one in the file which I thought wouldn’t fire as I have a die();
command in my own function. Can someone please point out where I am going wrong?