How to Create AJAX Forms Using the WordPress wp_nonce_field

What are WordPress nonces?

According to the codex, a nonce is a “number used once” to help protect URLs and forms from certain types of misuse, malicious or otherwise.

WordPress can create nonces for them to be submitted via form or another action, and on the other hand, it can verify the nonce passed in a form or an action is valid before accepting the associated data.

For more info about nonces, check out the WordPress codex.

The form

For this tutorial, we need to create two files: ajax.php, which will contain the code needed to process the request, and page-form.php, the main file, containing a simple form. Using a nonce adds an extra layer of security to WordPress themes and plugin you might create.

Those two files should be created in your WordPress theme directory. You can either use a FTP program or the cPanel provided by your website hosting to do so.

Let’s start by creating a simple HTML form in the page-form.php file.

<form id="myform">
  <div class="form-group">
    <label for="formGroupExampleInput">Example label</label>
    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
  </div>
  <div class="form-group">
    <label for="formGroupExampleInput2">Another label</label>
    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
  </div>

  <?php wp_nonce_field( 'my_nonce' ); ?>

  <input type="submit" id="submit" value="Submit" />

</form>

Nothing special about this form, except a call to wp_nonce_field() on line 11. This function creates a nonce and adds it to the form using a hidden field. Another hidden field is created by the same function to store the referer.

If you look at the source of your page-form.php file, you’ll see that the wp_nonce_field() function has outputted something similar to the following:

<input type="hidden" id="_wpnonce" name="_wpnonce" value="ad8a767ba0" />
<input type="hidden" name="_wp_http_referer" value="/myaccount/mypage/" />

For more information on the function, don’t hesitate to refer to the codex.

Sending the form using jQuery

Now, we’re going to use some jQuery to send our form.

jQuery( document ).ready(function() {
	jQuery( "#submit" ).click(function() {
		 jQuery.post( "https://yoursite.com/ajax.php", jQuery('#myform').serialize())
			.done(function( data ) {
			alert(data);
		}); 
		return false;
	});
});

The code is pretty self-explanatory: When the user attempts to send the form, jQuery sends an AJAX request to https://yoursite.com/ajax.php, with the serialized form as content.

Verifying the nonce using PHP

Once the data has been sent, we need to verify that the nonce is valid. Here’s the content of the ajax.php file to which jQuery has sent the data:

<?php
define( 'WP_USE_THEMES', false );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

if (!check_ajax_referer( 'my_nonce' )){
	wp_die();
}

// If the nonce is correct, process the data

Lines 2 and 3 are including WordPress in the file. This step is necessary since we need the WordPress core to be included in order to use WP functions.

On line 5, WordPress is checking for a nonce named my_nonce using the check_ajax_referer() function, which returns true if the nonce is valid.

If the nonce is not valid, wp_die() is called and the execution of the script will be terminated. Otherwise, the script will proceed your data as needed.