DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Reduce Frontend Complexity in ASP.NET Razor Pages Using HTMX
  • Build a Dynamic Web Form Using Camunda BPMN and DMN
  • Combine Node.js and WordPress Under One Domain

Trending

  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • Throughput vs Goodput: The Performance Metric You Are Probably Ignoring in LLM Testing
  • You Don't Get to Retrofit Trust: Why API Security Must Be Designed In, Not Bolted On
  • Why Your DLP Policies Fall Short the Moment AI Agents Enter the Picture
  1. DZone
  2. Coding
  3. Frameworks
  4. Securing WordPress AJAX Forms Using Nonces

Securing WordPress AJAX Forms Using Nonces

In this article, we will take a look at how you as a developer can use nonces to protect AJAX requests on a WordPress site.

By 
Jean-Baptiste Jung user avatar
Jean-Baptiste Jung
·
Apr. 10, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
8.4K Views

Join the DZone community and get the full member experience.

Join For Free

When creating a WordPress theme or plugin, AJAX is often used in order to enhance the user experience. In order to ensure security and protect your site against several types of attacks including CSRF, WordPress provides security tokens called nonces. In this article, I'll show you how to use nonces to protect AJAX requests on a WordPress site.

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 an FTP program or the cPanel provided by your web 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.

AJAX Form (document) WordPress

Published at DZone with permission of Jean-Baptiste Jung. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Reduce Frontend Complexity in ASP.NET Razor Pages Using HTMX
  • Build a Dynamic Web Form Using Camunda BPMN and DMN
  • Combine Node.js and WordPress Under One Domain

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook