I’m trying to do an AJAX request in an WordPress plugin. The request is initiated on the front page embedded in an article using a custom shortcode.
I tried to combine infos from the documentation and this tutorial.
However something is going wrong when testing that method… the AJAX query hook isn’t called.
This is how my page.php
script is called for short code delivery:
add_shortcode('testshortcode', 'TestShortCodeFunction');
function TestShortCodeFunction($attributes)
{
ob_start();
include(__DIR__.'/page.php');
return ob_get_clean();
}
This is my compacted test script page.php
:
<?php
add_action('wp_ajax_test', 'Test');
add_action('wp_ajax_nopriv_test', 'Test');
// do_action('wp_ajax_nopriv_test'); this calls Test()
function Test()
{
echo 'Hallo';
die();
}
?>
<script type='text/javascript'>
jQuery(document).ready(function() {
console.log("JS query started");
// The following does not call test()
jQuery.ajax({
type: "POST",
url: "http://127.0.0.1/wordpress/wp-admin/admin-ajax.php?action=test",
success: function(data) {
console.log("Query returned: "+data);
}
});
});
</script>
Output on the console is:
JS query started
Query returned: 0
The Test()
function is never call according to the PHP debugger.
The admin-ajax.php
is executed according to the network monitor (URL http://127.0.0.1/wordpress/wp-admin/admin-ajax.php?action=test
) but returns 0
.
Inside admin-ajax.php
do_action('wp_ajax_test')
is called according to the PHP debugger.
I’d be really surprised if you managed to make those Ajax action hooks work inside an Output Buffer.
AFAIK, we should only use PHP
ob_*
functions as last resort.Here’s a standard implementation. A JavaScript file will be enqueued inside the shortcode callback function, and inside it we fire a
document.ready
Ajax call. Theadmin-ajax.php
URL is passed to a JS object usingwp_localize_script
. Check the code comments for more info and the Codex for details on each WP function:And the JavaScript file (
ajax.js
) stored in the same folder as the plugin file:Here’s a similar answer of mine using OOP and jQuery commands to trigger the action. And an article of interest.