Accept AJAX call with serialized form data

When working with AJAX and Forms in WordPress I like to code in the ajax action to the form so serialize works out of the box. Actually I wrote an article on this last year: https://webdevstudios.com/2015/02/12/handling-ajax-in-wordpress/

But, you’re here for answers, not a blog article, so here’s the brief part of it. You have three parts here, first is the HTML form. You can take advantage of serialize() by putting the action in a hidden form field, here’s an example:

<form class="my_form">
    <?php wp_nonce_field( 'my_action_nonce' ); ?>
    <input type="hidden" name="action" value="my_action" />
    <!-- More fields here... -->
    <input type="submit" name="submit" value="Submit" class="submit_form_btn" />
</form>

Notice the hidden form field named action. Of course I kept the wp_nonce_field() since well, security issues.

The second part is the actual jQuery, as stated previously, you don’t need to access AJAX via the original jQuery object since you already passed it in as $, but it doesn’t harm anything really, just bad practice.

jQuery( document ).ready( function( $ ) {
    $( '.submit_form_btn' ).on( 'click', function( evt ) {
        // Stop default form submission
        evt.preventDefault();
        // Serialize the entire form, which includes the action
        var serialized = $( '.my_form' ).serialize();
        $.ajax( {
            url: ajaxurl, // This variable somewhere
            method: 'POST',
            data: serialized, // This is where our serialized data is
        } ).done( function( result ){
            // Handle the result here...
        } );
    } );
} );

I tried to comment the code as best I could, it should make more sense, but let me explain. First you stop the form submission by the preventDefault() method of the evt object, ( short for event ).

You then serialize the form data and store it in a variable. I suppose you could shortcut it and simply drop that into the data object, but that’s up to you.

The final part, well you need to see what you’re posting right? That’s where error_log and print_r come in handy, here’s how:

<?php

function handle_ajax() {
    // Here you verify your nonce
    if ( ! wp_verify_nonce( $_POST['_wpnonce'], 'my_action_nonce' ) ) {
        // You can either return, or use nifty json stuffs
        wp_send_json_error();
    }
    // Here you should get ALL your data in a $_POST variable
    // or you can actually do someting like this then check your error log

    error_log( print_r( $_POST, 1 ) );

    // This will print out the ENTIRE $_POST variable to your debug.log if you have it
    // enabled, if not, it goes to your PHP error log

}
add_action( 'wp_ajax_my_action', 'handle_ajax' );

Now that SHOULD handle your ajax for you, what you do with the data is up to you.