Submitting a form with ajax in Wordpress

I am trying to get the results of an ajax request in wordpress, but I am getting result of '0' in an alert box of javascript, so the form looks like this:

<form class="form" id="ajax-contact-form" action="#">                            
        <input type="text" name="name" id="name"  placeholder="Name" required="">
        <button type="submit" class="btn">Submit</button>
</form>

The javascript looks like this:

$('#ajax-contact-form').submit(function(e){

    $.ajax({ 
         data: {action: 'contact_form'},
         type: 'post',
         url: ajaxurl,
         success: function(data) {
              alert(data); // This prints '0', I want this to print whatever name the user inputs in the form. 

        }
    });

})

And the PHP:

add_action('wp_ajax_contact_form', 'contact_form');
add_action('wp_ajax_nopriv_contact_form', 'contact_form');

function contact_form()
{
echo $_POST['name'];    
}

Does anyone know if the code above is correct, I have also tried $_REQUEST['name'] and it doesnt work.

Thanks soo much,


Try something like this, you did not add the name parameter you are expecting in your PHP contact_form function, so you must add it to the data attribute in the jQuery ajax function call.

$('#ajax-contact-form').submit(function(e){
    var name = $("#name").val();
    $.ajax({ 
         data: {action: 'contact_form', name:name},
         type: 'post',
         url: ajaxurl,
         success: function(data) {
              console.log(data); //should print out the name since you sent it along

        }
    });

});

Revisiting the answer, year 2022. The Accepted answer is accepting BLINDLY any AJAX request without verifying WordPress Nonces. AJAX request should be validated as a legitimate request instead of a potentially nefarious request from some unknown bad actor.

  • @see https://developer.wordpress.org/plugins/javascript/enqueuing/#nonce

The first thing your AJAX handler should do is verify the nonce sent by jQuery with check_ajax_referer(), which should be the same value that was localized when the script was enqueued.

First we pass the AJAX url and create and pass our nonce through wp_localize_script(). wp_localize_script() must be called after the script has been registered using wp_register_script() or wp_enqueue_script().

<?php

wp_localize_script( 'script', 'localize',
    array(
        '_ajax_url' => admin_url( 'admin-ajax.php' ),
        '_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
    )
);

From our script.js file we declare our AJAX function.

$(function(){
    $('button').click(() => {
        $.ajax({
            type: 'POST',
            url: localize._ajax_url,
            data: {
                _ajax_nonce: localize._ajax_nonce,
                test: 'test',

                /**
                 * The action parameter is the The dynamic portion of the wp_ajax_{$action} action hook (Ajax action callback being fired).
                 * 
                 * @see https://developer.wordpress.org/reference/hooks/wp_ajax_action/
                 * @see https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/
                 */
                action: '_POST_action',
            },
            success: (res) => {
                console.log(res);
            }
        });
    });
});

And we process the result and send a JSON response back to an Ajax request.

<?php

add_action( 'wp_ajax__POST_action', function () {

    if ( check_ajax_referer( '_ajax_nonce' ) ) {

        $test = $_POST['test'];

        //...

        wp_send_json_success();

    } else {
        
        wp_send_json_error();

    };

} );