I am attempting to validate and submit a form using AJAX in WordPress, however, the response that I am getting is 0. According to the codex, this would seem to indicate that admin-ajax is unable to find the functions that I defined.
What am I doing wrong?
Code (Simplified for Demonstration Purposes)
<script type="text/javascript">
jQuery(function()
{
jQuery(document).on('click', '#test-button', function()
{
var name = jQuery("#name").val();
var AdminAJAX = <?php echo json_encode(admin_url('admin-ajax.php')); ?>;
var ajaxparams = {
action: 'jp_ajax_request',
name: name
};
jQuery.post( AdminAJAX, ajaxparams, function( response )
{
alert(response);
});
}
}
</script>
<?php
add_action( 'wp_ajax_jp_ajax_request', 'jp_ajax_process');
add_action( 'wp_ajax_nopriv_jp_ajax_request', 'jp_ajax_process');
function jp_ajax_process()
{
echo 'ajax response';
die();
}
?>
<form action="">
<input type="text" id="name">
<button id="test-button">Submit</button>
</form>
Your
add_action()
calls for the AJAX handlers are too late.Add these hooks earlier, the best action is probably
wp_loaded
:See also: Debug AJAX.
This code should be placed in a plugin or in your theme’s
functions.php
.