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(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 )

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';

<form action="">
    <input type="text" id="name">
    <button id="test-button">Submit</button>
  • I'm not sure about that but you don't need to json_encode the admin url and your add_action and jp_ajax_process should be in a plugin file or your functions.php file – RRikesh May 24 '13 at 7:28
  • I used json_encode so that I could access a PHP function from my javascript code. Is there a better way of doing it? – William May 25 '13 at 13:45

Your add_action() calls for the AJAX handlers are too late.

Add these hooks earlier, the best action is probably wp_loaded:

add_action( 'wp_loaded', 'register_ajax_handlers' );

function register_ajax_handlers()
    add_action( 'wp_ajax_jp_ajax_request', 'jp_ajax_process');
    add_action( 'wp_ajax_nopriv_jp_ajax_request', 'jp_ajax_process');

See also: Debug AJAX.

This code should be placed in a plugin or in your theme’s functions.php.

  • Thank you! So after I did your changes and moved the function to my functions.php, it is working. However, I think that it would make more sense to have the 'jp_ajax_process' function with the rest of the code for the forms and javascript (in order to keep everything pertaining to that form in a single file). Is that possible? – William May 24 '13 at 13:15
  • @William You could combine all these function in one class and hook the methods to different actions. – fuxia May 24 '13 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.