Handling Form Submissions in WordPress with Admin-Post and Admin-Ajax

WordPress provides incredible support for you to work with form submissions in your application. Whether you add a form in the admin or public facing areas, the built-in mechanism with the admin-post and admin-ajax scripts will allow you to handle your form requests efficiently.

In this article, I’ll show you how to handle custom form submissions using the WordPress API. I’ll walk you through the process of adding a custom form in the admin area of a plugin, handle the form submission via an HTML as well as an AJAX request, and write the form handler in PHP to validate, sanitize and process the form input.

While I’ll stay within the admin realms of WordPress, the same concepts are applicable while working with forms in the public facing areas.

I’ll also be making use of object-oriented programming constructs for the plugin; however, you can achieve the same result using procedural code as well. The practice plugin can be downloaded from here to follow along with the article.

Note: This article is intended for intermediate-advanced WordPress developers. It assumes that you have a working knowledge of HTML, JavaScript, jQuery, PHP and the WordPress Plugin API. If you’d like a refresher, I recommend that you read through the following:

Let’s get started by first understanding the built-in WordPress mechanism to handle a regular form post request.

Form Submissions with admin-post.php in WordPress

The gamut of hooks available in WordPress gives you great control over the flow of execution of your application. This is no different when it comes to processing forms. All you need is the correct hook to ‘hook into’ and add the custom form handler. The hooks for processing custom forms are dynamic in nature, meaning that the name of the hook partly depends on you.

To process submissions related to your form only, you need finer control as shown below:

WordPress form submission with admin-post.php
WordPress form submission with admin-post.php

This is done by pointing the form submission to the admin-post.php file located in the wp-admin directory of WordPress, and including a custom name for the action in the form. On doing so, WordPress will trigger two action hooks based on the logged in status of the user:

  • admin_post_{$action} for logged in users
  • admin_post_nopriv_{$action} for non-logged in users

Where $action is the name of the action that was passed through the form.

You can then use add_action to tie the PHP form handler to the triggered hooks, where you will have full control to process the form data with the $_GET and $_POST variables.

As you may have guessed already, despite its name, admin-post.php can handle POST and GET requests as well as requests for admin and non-admin areas of the application.

Let’s explore this with the help of a custom plugin.

The Object-Oriented Plugin Structure

My goal here is to help you understand everything that goes behind processing custom forms in WordPress with and without AJAX. For this article, I’ve prepared a custom plugin that you can download from here to follow along. I recommend that you have it open in a suitable editor and install it on a local WordPress setup only.

I built the plugin using object-oriented programming practices with the help of a plugin boilerplate. Boilerplate Starting Points are among the many best practices listed in the WordPress Plugin Handbook. They’re a great way to ensure consistency across your plugins, and save you a lot of time writing standard code. Over a period, you may even end up writing your own custom boilerplate based on your coding preferences. That’s what I did.

The plugin is based on my own plugin template which is a fork of the original WordPress Plugin Boilerplate project. It’s similar to the original project in many aspects but also has support for namespaces and autoloading. This way I don’t need to have unique prefixes for every class or function, and don’t end up with a lot of include and require statements. However, the minimum required PHP version for my plugin is 5.6.0.

Note: If you don’t use namespaces or use procedural code you must prefix everything.

Here’s how the plugin is structured in the backend:

  • inc/core/* – core functionality of the plugin
  • inc/admin/* – functionality related with the admin area
  • inc/frontend/* – functionality related with the public facing areas
  • inc/common/* – functionality shared between the admin and the frontend
oop-based-plugin structure
Plugin structure in the backend

The plugin has a top-level admin menu with two menu items for the form pages.

admin menu structure of the plugin
Admin menu structure of the plugin

To see how I added the admin menu pages, take a look at the define_admin_hooks() method in inc/core/class-init.php and the add_plugin_admin_menu() method in the inc/admin/class-admin.php of the plugin.

If you’d like to know more about adding admin pages to your plugin, have a look at our article about creating WordPress admin pages here.

Adding the Form to the Admin Page of the Plugin

When I added the “HTML Form Submit” menu page for the plugin, I had to also specify the callback to load the page content. This is where the form is added.

However, instead of directly writing the HTML in the html_form_page_content method, I used another file partials-html-form-view.phplocated in inc/admin/views for the form HTML and loaded it in the callback as shown below:

This is purely a coding preference. It allows me to keep my code readable by separating the HTML, and makes no difference to the output of the form on the plugin page.

plugin admin page with html form
HTML Form in the admin page of the plugin

Understanding Form Security, Structure, and Submission

The form that was added above has a select field with a drop-down list of existing WordPress users and two text fields for user input. However, this simple example has a lot going on behind the scenes. The form code below is self-explanatory, so let’s walk through the important elements:

Form Security

The most important thing to keep in mind when dealing with forms in the admin area of WordPress is security. Secure your form using a combination of both WordPress Nonces and current_user_can( $capability ). In my example, I’ve restricted entry to the form with if( current_user_can( 'edit_users' ) ), i.e. the form will be loaded only if the logged in user has the edit_users capability.

I also generated a custom nonce by using wp_create_nonce() and then added it as a hidden form field. You can instead use wp_nonce_field() to add it directly. Here’s a great article to understand Nonces in detail.

Form Structure

I’ve prefixed all form elements with the plugin name to ensure uniqueness. This is again a personal coding preference, as I can be sure of targeting only my form elements through JavaScript. I’ve also used the HTML5 required attribute to leave form validation to the browser.

plugin form inspect view in chrome
Inspecting the admin form

Form Submission

The form submission is made to the admin-post.php using the admin_url( 'admin-post.php' ) function rather than hardcoding the URL. When WordPress receives the form, it will look for the value of the action field to trigger the form hooks. In my case, it will generate the admin_post_nds_form_response hook. Had it been a page open to the public view, it would have triggered the admin_post_nopriv_nds_form_response hook.

The Form Handler for the POST request

At this stage, if you submit the form, you’ll be redirected to an empty page with the page URL set to the admin-post.php. This is because there is no form handler to process the request yet. To process the request, I registered my custom handler the_form_response in the define_admin_hooks() method of class-init.php like this: $this->loader->add_action( 'admin_post_nds_form_response', $plugin_admin, 'the_form_response');

If you were using procedural code you would simply do add_action( 'admin_post_nds_form_response', 'the_form_response');

the_form_response() is where I’ll have full access to the form data via the $_POST or $_GET superglobals. As shown below, I added a breakpoint to the callback in my IDE to be certain that the hook would work as expected.

pausing php script execution
Inspecting form input with XDebug

Form Validation and Input Sanitization

Before performing any operations, you must validate the nonce and sanitize the user input properly. I made use of the wp_verify_nonce( $nonce_name, $nonce_action ) function to verify the nonce, and sanitize_key() and sanitize_text_field() functions to sanitize the user input available in the $_POST variable. If the nonce verification fails, the user will get an error message as the server response, using the wp_die() WordPress function.

Note: I accessed the form data using the $_POST variable. Had I submitted the form using the get method, I would instead make use of the $_GET or $_REQUEST global variable.

Only when I’m sure that everything is in order, would I perform a WordPress operation like adding the user-meta to the selected user.

To know more about input sanitization, I recommend that you read through the WordPress Codex: Validating Sanitizing and Escaping User Data here.

Submitting the Server Response

After performing the server operations, it’s important to send the server response back to the user. To do this, you will first need to redirect the user back to an admin page or one that provides some feedback. I redirected the user back to the plugin page and used WordPress admin notices to display the server feedback. The server response in my example simply outputs the $_POST variable as a WordPress admin notice.

form post server response
Server response from the form handler

Progressive Enhancement

At this stage, I have a fully functional form in the admin area of my WordPress plugin. It’s secure and submits properly to my form handler, where the input data is sanitized and finally, the server response is visible. The form will work out of the box in all browsers that have support for HTML5. But there’s a lot I can do to improve the user experience such as adding AJAX support.

This approach of establishing a basic level of user experience that’s available in all browsers, and then adding advanced functionality for browsers that support it is called Progressive Enhancement.

Note: I’ve made the assumption that my users use modern browsers with HTML5 support. However, if the form had to be rendered on an older browser, the built-in HTML5 input validation for required fields would break. Can I Use is a great website that you can use to compare web features that are available across browsers and browser versions.

Form Submissions with AJAX (admin-ajax.php) in WordPress

AJAX in WordPress is handled via the wp-admin/admin-ajax.php file. Here’s an overview of how custom forms can be processed via AJAX in WordPress:

form support with ajax
Form submission with AJAX support in WordPress

You’ll notice that it’s quite similar to how forms are processed using admin-post.php. When WordPress receives an AJAX request it will create two hooks based on the supplied action:

  • wp_ajax_{$action} for logged in users
  • wp_ajax_nopriv_{$action} for non-logged in users

Where $action is the name of the action that was passed.

Adding AJAX Support to the Plugin Form

The second menu page of the plugin “Ajax Form Submit” loads the form that’s submitted via an AJAX request. It’s added to the menu page in the same manner as discussed earlier, and uses the partials-ajax-form-view.php file to load the form content. If you look at this file, you’ll notice that it’s nearly identical to the earlier form with the only differences being the value of the form id attribute and the title. Now that I can identify one form from the other, I can process just the second form via AJAX using JavaScript.

To add AJAX support, I performed the following steps:

  • Enqueued a JavaScript file to load the jQuery
  • Used jQuery submit event handler to prevent the normal form submission
  • Used jQuery.ajax() to submit the form to admin-ajax.php instead of admin-post.php

Note: If for some reason JavaScript is disabled in the browser, jQuery or AJAX will be unavailable too, but the form will still submit normally. This is because I left the form submission URL as admin-post.php in the form HTML.

Using JavaScript and jQuery to Post the Form

Here’s the JavaScript that I used to submit the form via AJAX.

event.preventDefault(); is what actually prevents the normal form submission.

I gathered the form data using jQuery’s serialize() function but there are many other ways to do this. One of them is using HTML5’s FormData interface. It’s beyond the scope of this article but it’s definitely worth looking at.

var ajax_form_data = $("#nds_add_user_meta_ajax_form").serialize();

I also added additional URL parameters to the serialized data, so I can distinguish between an AJAX and a regular request in the PHP form handler later.

ajax_form_data = ajax_form_data+'&ajaxrequest=true&submit=Submit+Form';

Typically, the X-Requested-With HTTP header is automatically set to XMLHttpRequest by the AJAX library. This can also be used to identify an AJAX request but it’s not always reliable.

The ajax() method of jQuery will submit the request to the server.

To get the form to submit to admin-ajax.php, I used an array params.ajaxurl that was passed in from PHP using wp_localize_script.

Note: The form data in my example includes the action that WordPress will use to generate the hooks for the AJAX request. The following hooks will be triggered by WordPress:

  • wp_ajax_nds_form_response for logged in users
  • wp_ajax_nopriv_nds_form_response for non-logged in users

The JavaScript file is enqueued in the enqueue_scripts() method of class-admin.php as below:

The ajaxurl Global Variable

You can also use a global JavaScript variable ajaxurl instead of passing the URL for admin-ajax.php from PHP. However, the variable is available only when dealing with the admin end and is unavailable when dealing with AJAX on the frontend.

Depending on the response from the server, the AJAX promise callbacks .done() and .fail() will execute accordingly. In my example, for a successful request, I’ve added the response to the empty div container #nds_form_feedback that was part of my form HTML. Finally, the fields are cleared by reseting the form.

The Form Handler for the AJAX Request

I’ve attached the same form handler the_form_response to the AJAX request as well.

And in the form handler, I used $_POST['ajaxrequest'] that was set manually in the JavaScript to distinguish between a normal and AJAX request.

pausing script execution to verify ajax
Validating the AJAX request using a breakpoint

That’s it. With AJAX, the response is displayed without the page being reloaded or redirected.

If JavaScript was disabled or did not load for some reason, $_POST['ajaxrequest'] would not be valid, and the form would submit normally by skipping the AJAX specific if( isset( $_POST['ajaxrequest'] ) && $_POST['ajaxrequest'] === 'true' ) code block.

You can certainly do a lot more to improve the user experience, and I recommend you read through the jQuery API documentation for AJAX here.

Additional Resources

We’ve covered a lot of ground here. AJAX is a fairly vast topic and is implemented in several ways. Here are some more examples of using AJAX in WordPress:

Using AJAX and PHP in Your WordPress Site Creating Your Own Plugin

Good design is invisible! It’s like an air conditioner set on automatic temperature control. Until you feel too hot or cold, you don’t pay any attention to it, concentrating instead on the task at hand, or just enjoying your time.

For users surfing the web, Ajax is like an automatic air conditioner. It makes websites smoother and faster to use, resulting in a pleasurable experience. And most importantly, it just works!

If you prefer a video instead, you’re in luck!

Learn how to use Ajax Easily:

What is Ajax Exactly?

Ajax is a web development technique that stands for Asynchronous JavaScript And XML. It’s used to create dynamic web applications that are interactive and fun. With Ajax, you don’t have to wait for the web page to reload to see a change. Everything’s taken care of automatically in the background without disrupting what you’re doing, thereby enhancing your user experience.

Ajax at work!

You’ve probably come across Ajax on the web already. Google Search’s autocomplete feature is perhaps the most popular one. Google Maps is another. Live refresh of tweets, Facebook comments, Reddit posts, YouTube likes, all these incredible user experiences are made possible thanks to Ajax and related technologies.

In this post, I’ll give you a quick intro to Ajax, list its advantages, explain how it works in WordPress, and then we’ll dive headfirst into creating a simple WordPress Ajax Plugin.

Sounds fun? Let’s get started.

The Basics of Ajax

Ajax uses a combination of programming languages such as HTML/CSS, JavaScript, XML/JSON, and a server-side scripting language (PHP, ASP.NET, etc.). It works by sending data from the browser to the server, which processes it and sends back a response. This response is used by the browser to update the web page without reloading it.

Here’s how it usually goes:

  • A user action triggers an event in a browser (like a button click).
  • The Ajax call activates, which sends a request to the server, using XML/JSON.
  • The server-side script processes this request. It can also access the database if it needs to.
  • The server then sends a response back to the browser.
  • A second JavaScript function, called a callback function, receives the response and updates the web page.
infographic illustrating the basics of Ajax

The Many Advantages of Ajax

  1. Minimizes bandwidth usage and optimizes network operations, as the servers won’t be required to process loads of data.
  2. Saves time for both the users and the server, as the user can see the response from the server immediately.
  3. Increased performance. Since no full-page data is being sent, Ajax improves the performance, speed, and usability of web pages/apps.
  4. Increased responsiveness. By eliminating full-page reload, websites will be swifter and highly responsive, thus more user-friendly.

Skills Needed to Work with Ajax in WordPress

  • Knowledge of HTML, CSS, and JavaScript (jQuery is enough)
  • Basic familiarity with XML or JSON data interchange formats
  • Know-how of PHP for server-side scripting

If your jQuery or PHP knowledge is touch and go, don’t fret! You can still follow the tutorial logic. Feel free to hop into the comments section if you’re stuck or need help with something :)

Intro to Ajax in WordPress

The core of WordPress already uses Ajax, but only in the admin screens. For instance, when you’re moderating comments or adding/deleting items from categories or posts, you can see instant updates thanks to Ajax. It’s also the tech behind the much loved auto-save functionality.

Ajax is most commonly used with jQuery functions on WordPress, as it’s much simpler when compared to VanillaJS. Moreover, WordPress core already comes loaded with the jQuery library.

Here’s what the process for using Ajax in WordPress looks like:

  1. The user triggers an Ajax request, which is first passed to the admin-ajax.php file in the wp-admin folder.
  2. The Ajax request needs to supply at least one piece of data (using the GET or POST method). This request is called the action.
  3. The code in admin-ajax.php uses the action to create two hooks: wp_ajax_youraction and wp_ajax_nopriv_youraction. Here, youraction is the value of the GET or POST variable action.
  4. The first hook wp_ajax_youraction executes only for logged-in users, while the second hook wp_ajax_nopriv_youraction caters exclusively for logged-out users. If you want to target all users, you need to fire them both separately.
  5. Plan the hook functions for graceful degradation. It ensures that your code will work even on browsers with JavaScript disabled.
Infographic illustrating how Ajax is used with WordPress

Let’s Create a WordPress Ajax Plugin

Every great journey begins with a single step, and so does our learning. Let us build a basic WordPress plugin called Post Likes Counter with the following features:

  • Logged-in users can like posts.
  • The plugin keeps a tally of the total number of post likes and displays them.
  • The post likes counter is updated instantaneously on the front-end.
  • Logged-out users will be shown an error message if they attempt to like a post.

To start, create an empty WP plugin and activate it. If you need help with this, you can refer to our WordPress plugin development guide. WordPress Codex also has a detailed page on writing a WP plugin.

Find Your Theme’s Post Template

After that, you need to find your theme’s single.php post template. It’s used when a single post is queried, which is where we want our post likes counter to be. This file can be found in the root folder of your active theme. Keep it open for editing.

Get the Post Template Ready for an Ajax Call

Let’s create a link here to let users like posts. If a user has JavaScript enabled, it’ll use the JavaScript file we’ll create later; if not, it’ll just follow the link directly. Place the code given below in your single.php file.

Alternatively, you can add this code to any of the template parts your single.php file includes. For instance, if you’re using the official Twenty Nineteen theme, you can insert this code in your theme’s content-single.php file. For testing this plugin code, I inserted it in this file at the very end of its div.entry-content section.

Addressing the Ajax Call Without JavaScript

Clicking the link created above will take you to the admin-ajax.php script, but you won’t see any useful output as you’ve not created any function yet to run your action.

To do that, create a function in your plugin file and add it to the two hooks that were created by WordPress for you. Follow the code shown below:

If everything checks out, when a logged-in user clicks the Like this Post link, the like counter above it should increase by 1 automatically. For browsers with JavaScript disabled, the page will refresh, but it’ll still show the updated like count.

The function to handle logged-out users doesn’t do much here except for throwing up an error message. It’s only meant to serve as an example. You can, of course, build on this and give your visitors more helpful options.

Finally, Adding Support for JavaScript

It’s a good practice to add support for JavaScript towards the end, as it makes things much clearer. To use Ajax on WordPress, you need to enqueue jQuery library as well as your plugin’s custom JavaScript file. For this, go to your plugin and append the following script:

Once that’s done, it’s time to create the liker_script.js JavaScript file. Then you have to upload this file to the location referenced in the previous code (hint: it’s your plugin’s root folder). Here’s the code for liker_script.js:

The my_user_like() function defined in our plugin should send our browser a response as a JSON-encoded result array, which can also be used as a JavaScript object. Using this, we can update the post like count without reloading the web page.

And that’s it! Hurrayyyyyy!

You’ve now enabled Ajax functionality for your plugin. Of course, you can expand on this and add more features as per your liking. Go ahead, tweak it till you make it!

Screenshot showing our simple post like counter on the frontend of a post. "Like this post" link that increases the count each time you click it.
Our simple post like counter. You can add styles, animations, and other scripts to level it up.

Notable WordPress Plugins Which Use Ajax

Need some Ajax inspiration to fire you up? Check out these amazing WordPress plugins that use the power of Ajax to build powerful features and smoother user experiences.

  1. Lazy Load Plugins
    Lazy Loading is a web development technique used to improve initial page loading time. It’s done by delaying the loading of resource-heavy assets that aren’t visible to the user in their browser’s viewport. These assets are loaded automatically when the user scrolls down the web page. The free version of Smush supports lazy loading.
  2. Forminator
    A completely expandable form maker plugin that also supports polls, quizzes, order forms with payment options, etc. It has an option to enable form submissions with Ajax, making it a seamless experience for the users.
  3. Login With Ajax
    Power your WordPress site with smooth Ajax login and registration effects with this feature-rich plugin. If you’re looking to give your users a better login and registration experience than the default WordPress one, look no further.
  4. WP-PostRatings
    This simple plugin adds an Ajax rating system for your WordPress website’s posts and pages. It also adds shortcode support for the ratings, so that you can display them anywhere you want.
  5. YITH WooCommerce Ajax Product Filter
    An extremely helpful and powerful plugin for WooCommerce that lets you apply the exact filters you need to display the product variations you’re looking for. Ajax makes sure that it all happens in a jiffy.
  6. Ajax Search Lite
    A responsive, live search plugin for WordPress, powered by Ajax. It also includes Google autocomplete and keyword suggestions. Give your users a better search experience on your website with this plugin.
  7. Simple Ajax Chat
    Have you ever wondered if you could chat with other users on a website, live? This Ajax-powered plugin is the answer to that. It’s mobile compatible and is built to be extremely customizable as per your liking.

Head over to WordPress.org’s plugin repository for more brilliant Ajax implementations.

Keep Calm and Ajax On!

What’s good for the <body> is good for the user and server too, but you need to balance it out. Ajax is a powerful tool in your arsenal to enhance website performance and user experience. But you should only use it where it’s necessary. Always focus on the user experience aspect. It’ll be a bit rough in the beginning, but once you’ve mastered the basics of Ajax, there’s no stopping you!

10 Best Practices for Ajax Implementations

Ajax technology implementation optimizes efficiency and aids in building better as well as more interactive web applications.

Ajax technology implementation is a collection of web development methods that creates asynchronous web applications by combining several professional web services. This technology allows the use of web applications to transmit and receive data dynamically without disturbing the display of the whole page. Its benefits are similar to that of WordPress.

Java HTML Report in a Few Lines of Code (Part 2)

In the previous article, I described the creation of an HTML table report with AJAX filtering and user sorting of columns — using a few lines of code written into a single Java command. For this, I used the ReportBuilder class from the Ujorm framework. Today, I’d like to show you how to place formatted content into the cells of such a table, as well as a few more improvements. What will the final table look like?

Our filter now has a new input field for limiting the number of displayed rows. We can insert the first column into our table, containing the sort order number of the row. The star classification of a hotel can be displayed using a list of appropriate characters with a tooltip, and the final column contains a link to the hotel home page. The original behaviour of the table remains the same, the updated source code is here:

A Simple AJAX Website in Java

During the Covid New Year of 2020, I created a simple prototype website using AJAX, with the goal of moving Java developers away from JavaScript and ideally also text-based HTML templates. The developer will however need to understand the structure of an HTML page as well as CSS selectors. I made my original solution a little more general, moved certain parts into the Ujorm framework, and am presenting the result here for your further inspiration.

For the prototype to make any sense, I created a web page for testing regular expressions. Let’s take a look at the code, worked into a regular Java servlet:

Spring — DWR — Ext JS Chat Application

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-kabootar

I was curious to explore the capabilities of Reverse Ajax. That's when I created this simple chat application using Spring/DWR/Ext JS.

From my experience, I can easily say that DWR is easy to learn and configure, especially when you are planning to integrate with Spring on the application tier. DWR has a powerful API to perform all relevant operations, right from accessing page script sessions to util classes for sending updates to the client.


I used Ext JS for creating the user interface, which renders stunning displays for elements like forms, buttons, etc. Ext JS has a very steep learning curve and each operation requires a lot of configuration and reference. Also, I found that the event handling mechanism, though complete, is very complex to use. I relied on external Javascript coding for handling events. On the upside, the documentation and support are really good for this framework. Despite this, I would instantly recommend the use of Ext JS for large-sized customer-facing web-based applications, especially for the internet. For medium-scale projects or enterprise-based projects, I would think twice.


An Introduction To Stimulus.js

An Introduction To Stimulus.js

An Introduction To Stimulus.js

Mike Rogers

The web moves pretty fast and picking an approach for your frontend that will feel sensible in a year’s time is tricky. My biggest fear as a developer is picking up a project that hasn’t been touched for a while, and finding the documentation for whatever approach they used is either non-existent or is not easily found online.

About a year ago, I started using Stimulus and I felt really happy about the code I was shipping. It’s a ~30kb library which encourages small reusable sprinkles of JavaScript within your app, organized in such a way that it leaves little hints in your accessible HTML as to where to find the JavaScript it’s connected to. It makes understanding how a piece of JavaScript will interact with your page almost like reading pseudocode.

Stimulus was created by the team at Basecamp — they recently released the HEY email service — to help maintain the JavaScript they write for their web applications. Historically, Basecamp has been quite good around maintaining their open-source projects, so I feel quite confident that Stimulus has been tested thoroughly, and will be maintained for the next few years.

Stimulus has allowed me to build applications in a way that feels reusable and approachable. While I don’t think Stimulus will take over the web like React and Vue have, I think it is a worthwhile tool to learn.

Terminology

Like all frameworks, Stimulus has preferred terms for describing certain things. Luckily (and one of the main reasons I’ve taken to liking Stimulus), there are only two you’ll need to know about:

  • Controller
    This refers to instances of JavaScript classes which are the building blocks of your application. It’s safe to say that when we talk about Stimulus Controllers, we’re talking about JavaScript classes.
  • Identifier
    This is the name we’ll use to reference our controller in our HTML using a data attribute that is common to Stimulus codebases.

Let’s Jump Into Stimulus!

In the following few examples, I’m going to use code you can drop into the browser to get started right away via the library distributed via unpkg.com. Later on, I’ll cover the webpack approach which is highly encouraged as it allows for improved organization of your code and is the approach used in the Stimulus Handbook.

The Boilerplate

See the Pen [The Boilerplate - Stimulus](https://codepen.io/smashingmag/pen/abdjXvP) by Mike Rogers.

See the Pen The Boilerplate - Stimulus by Mike Rogers.

Once you understand the gist of the above snippet, you’ll have the knowledge to be comfortable picking up a project that uses Stimulus.

Pretty awesome, right? Let’s jump into what everything is doing!

application.start

This line tells Stimulus to add the listeners to the page. If you call it just once at the top of your page before you add any Stimulus code, it’ll return an instance of the main Stimulus controller which includes the method register that is used to tell Stimulus about the classes you’d like to connect to it.

Controllers

The data-controller attribute connects our HTML element to an instance of our JavaScript class. In this case, we used the identifier “counter” to hook up an instance of the CounterController JavaScript class to our div element. We told Stimulus about the connection between this identifier and the controller via the application.register method.

Stimulus will continuously monitor your page for when elements with this attribute are added and removed. When a new piece of HTML is added to the page with a data-controller attribute, it’ll initialize a new instance of the relevant controller class, then connect the HTML element. If you remove that element from the page, it’ll call the disconnect method on the controller class.

Actions

Stimulus uses a data attribute data-action to clearly define which function of the controller will be run. Using the syntax event->controller#function anyone reading the HTML will be able to see what it does. This is especially useful as it reduces the risk of unexpected code from other files, making it easier to navigate the codebase. When I first saw the approach Stimulus encourages, it felt almost like reading pseudocode.

In the above example, when the button fires the “click” event, it will be passed onto the addOne function within our “counter” controller.

Targets

Targets are a way to explicitly define which elements are going to be available to your controller. Historically I’ve used a mix of ID, CSS class names and data attributes to achieve this, so having a single “This is the way to do it” which is so explicit makes the code a lot more consistent.

This requires defining your target names within your controller class via the targets function and adding the name to an element via the data-target.

Once you’ve got those two pieces setup, your element will be available in your controller. In this case, I’ve set up the target with the name “output” and it can be accessed by this.outputTarget within the functions in our controller.

Duplicate Targets

See the Pen [Duplicate Targets - Stimulus](https://codepen.io/smashingmag/pen/ExPprPG) by Mike Rogers.

See the Pen Duplicate Targets - Stimulus by Mike Rogers.

If you have multiple targets with the same name, you can access them by using the plural version of the target method, in this case when I call this.outputTargets, it’ll return an array containing both my divs with the attribute data-target="hello.output".

Event Types

You listen for any of the events you’d commonly be able to attach via the JavaScript method addEventListener. So for example, you could listen for when a button is clicked, a form is submitted or an input is changed.

See the Pen [Event types - Stimulus](https://codepen.io/smashingmag/pen/wvMxNGJ) by Mike Rogers.

See the Pen Event types - Stimulus by Mike Rogers.

To listen to window or document events (such as resizing, or the user going offline), you’ll need to append “@window” or “@document” to the event type (e.g. resize@window->console#logEvent will call the function logEvent) on the console controller when the window is resized.

There is a shorthand way to attach common events, where you are able to omit the event type and it has a default action for the element type. However, I strongly discourage using the event shorthand, as it increases the amount of assumptions someone who is less familiar with Stimulus needs to make about your code.

Uses Multiple Controllers In The Same Element

Quite often you may want to break out two pieces of logic into separate classes, but have them appear close to each other within the HTML. Stimulus allows you to connect elements to multiple classes by placing references to both within your HTML.

See the Pen [Multiple Controllers - Stimulus](https://codepen.io/smashingmag/pen/XWXBOjy) by Mike Rogers.

See the Pen Multiple Controllers - Stimulus by Mike Rogers.

In the above example, I’ve set up a basket object which only concerns itself with counting the total number of items in the basket, but also added a child object that shows the amount of bags per item.

Passing Data To Your Object

See the Pen [Passing Data - Stimulus](https://codepen.io/smashingmag/pen/mdVjvOP) by Mike Rogers.

See the Pen Passing Data - Stimulus by Mike Rogers.

Stimulus provides the methods this.data.get and this.data.set within the controller class, this will allow you to change data attributes which are within the same namespace as the identifier. By this I mean if you want to pass data to your stimulus controller from your HTML, just add an attribute like data-[identifier]-a-variable to your HTML element.

When calling this.data.set, it will update the value in your HTML so you can see the value change when you inspect the element using your browser development tools.

Using namespaced data attributes is a really nice way to help make it really clear which data attribute is for what piece of code.

Initialize, Connected, Disconnected

As your application grows, you’ll probably need to hook into ‘lifecycle events’ to set defaults, fetch data, or handle real-time communication. Stimulus has three build-in methods which are called throughout the lifecycle of a Stimulus class.

See the Pen [Initialize, Connected, Disconnected - Stimulus ](https://codepen.io/smashingmag/pen/ZEQjwBj) by Mike Rogers.

See the Pen Initialize, Connected, Disconnected - Stimulus by Mike Rogers.

When Stimulus sees an element with a matching data-controller attribute, it will create a new version of your controller and call the initialize function. This will often run when you first load the page, but will also be run if you were to append new HTML to your page (e.g. via AJAX) containing a reference to your controller. It will not run when you move an element to a new position within your DOM.

After a class has been initialized, Stimulus will connect it to the HTML element and call the connect function. It’ll also call connect if you were to move an element within your DOM. So if you were to take an element, remove it from one element, then append it somewhere else, you’d notice only connect will be called.

The disconnect function will be run when you remove an element from your page, so for example, if you were to replace the body of your HTML, you could tear down any code which might need to be rerun if the element isn’t in the same position. For example, if you had a fancy WYSIWYG editor which adds lots of extra HTML to an element, you could revert it to its original state when disconnect was called.

Inheriting Functionality

On occasion, you may want to share a little common functionality between your Stimulus controllers. The cool thing about Stimulus is that (under the hood) you’re connecting somewhat vanilla JavaScript classes to HTML elements, so sharing functionality should feel familiar.

See the Pen [Inheriting functionality - Stimulus](https://codepen.io/smashingmag/pen/JjGBxbq) by Mike Rogers.

See the Pen Inheriting functionality - Stimulus by Mike Rogers.

In this example, I set up a parent class named ParentController, which is then extended by a child class named ChildController. This let me inherit methods from the ParentController so I didn’t have to duplicate code within my ChildController.

Using It In Production

I demonstrated some fairly stand-alone examples of how to use Stimulus above, which should give you a taste of what you can achieve. I also thought I should touch on how I use it in production and how it has worked out for me.

Webpack

If you’re using Webpack, you’re in for a treat! Stimulus was totally made to be used with Webpack. Their documentation even has a lovely starter kit for Webpack. It’ll allow you to break your controllers into separate files and Stimulus will decide on the correct name to use as an identifier.

You don’t have to use webpack if you want to use Stimulus, but it cleans up the experience a bunch. Personally, Stimulus was the library that helped introduce me to Webpack and really feel the value it offered.

Filename Conventions

I mentioned in the introduction of this article that I enjoyed using Stimulus because it felt organized. This really becomes apparent when you are combining it with Webpack, which enables auto loading and registration of controllers.

Once you’ve set up Stimulus in Webpack, it’ll encourage you to name your files like [identifier]_controller.js, where the identifier is what you’ll pass into your HTMLs data-controller attribute.

As your project grows, you may also want to move your Stimulus controllers into subfolders. In a magical way, Stimulus will convert underscores into dashes, and folder forward slashes into two dashes, which will then become your identifier. So for example, the filename chat/conversation_item_controller.js will have the identifier chat--conversation-item.

Maintaining Less JavaScript

One of my favorite quotes is “The Best Code is No Code At All”, I try to apply this approach to all my projects.

Web browsers are evolving a lot, I’m pretty convinced that most of the things I need to write JavaScript for today will become standardized and baked into the browser within the next 5 years. A good example of this is the details element, when I first started in development it was super common to have to manually code that functionality by hand using jQuery.

As a result of this, if I can write accessible HTML with a sprinkling of JavaScript to achieve my needs, with the mindset of “This does the job today, but in 5 years I want to replace this easily” I’ll be a happy developer. This is much more achievable when you’ve written less code to start with, which Stimulus lends itself to.

HTML First, Then JavaScript

One aspect I really like about the approach Stimulus encourages, is I can focus on sending HTML down the wire to my users, which is then jazzed up a little with JavaScript.

I’ve always been a fan of using the first few milliseconds of a user’s attention getting what I have to share with them — in front of them. Then worrying setting up the interaction layer while the user can start processing what they’re seeing.

Furthermore, if the JavaScript were to fail for whatever reason, the user can still see the content and interact with it without JavaScript. For example, instead of a form being submitted via AJAX, it’ll submit via a traditional form request which reloads the page.

Conclusion

I love building sites that need just small sprinkles of maintainable JavaScript to enhance the user experience, sometimes it’s nice to just build something which feels simpler. Having something lightweight is great, I really love that without too much cognitive load it’s pretty clear how to organize your files, and set up little breadcrumbs that hint about how the JavaScript will run with a piece of HTML.

I’ve really enjoyed working with Stimulus. There isn’t too much to it, so the learning curve is fairly gentle. I feel pretty confident that if I was to pass my code onto someone else they’ll be happy developers. I’d highly recommend giving it a try, even if it’s just out of pure curiosity.

The elephant in the room is how does it stack up compared to the likes of React and Vue, but in my mind, they’re different tools for a different requirement. In my case, I’m often rendering out HTML from my server and I’m adding a little JavaScript to improve the experience. If I was doing something more complex, I’d consider a different approach (or push back on the requirements to help keep my code feeling simple).

Further Reading

  • Stimulus Homepage
    They have a fantastic handbook that goes into the concepts I’ve outlined above into a lot more depth.
  • Stimulus GitHub Repository
    I’ve learned so much about how Stimulus works by exploring their code.
  • Stimulus Cheatsheet
    The handbook summarized on a single page.
  • Stimulus Forum
    Seeing other people working with Stimulus has made me really feel like it’s being used in the wild.
Smashing Editorial (sh, ra, yk, il)

Avoid This Common Anti-Pattern in Full-Stack Vue/Laravel Apps

If you want your Vue.js single-page app to communicate with a Laravel backend, you will, quite reasonably, think of using AJAX. Indeed, Laravel comes with the Axios library loaded in by default.

However, it's not advisable to use AJAX to retrieve application state on the initial page load, as it requires an extra round-trip to the server that will delay your Vue app from rendering.

4 AJAX Patterns for Vue.js Apps

If you ask two Vue.js developers "what's the best way to use AJAX in an app?" you'll get three different opinions.

Vue doesn't provide an official way of implementing AJAX, and there are a number of different design patterns that may be used effectively. Each comes with its own pros and cons and should be judged based on the requirements. You may even use several simultaneously!

How to Build a WordPress AJAX Form (in 4 Easy Steps)

Do you want to build an AJAX contact form in WordPress?

AJAX contact forms allow users to submit the form without reloading a page. This enables you to increase user engagement while offering a better form submission experience to your users.

This comes in handy when you run an eCommerce website and want to collect user feedback without diverting user attention.

You can also use the same AJAX functionality for other custom forms on your website. For example, a custom user login form will allow users to login without an additional page load.

In this article, we will show you how to easily build a WordPress AJAX contact form with step by step instructions.

Creating an Ajax contact form in WordPress

What is Ajax and Why Use it For Your Forms?

Ajax, short for Asynchronous Javascript and XML, is a JavaScript programming technique which allows developers to transfer data without reloading a page.

It is most commonly used in web forms allowing users to submit form data without reloading a page. This makes form submission easy and fast, which improves the overall user experience.

Web applications like Gmail and Facebook extensively use this technique to keep users engaged while making everything work seamlessly in the background.

You can also use Ajax for your WordPress forms. It will save users from unnecessary page reload and keeps them engaged on the page they are currently viewing.

That being said, let’s take a look at how to easily make a WordPress Ajax contact form in 4 simple steps.

1. Install WPForms Plugin

First thing you need to do is install and activate the WPForms plugin. For more details, see our step by step guide on how to install a WordPress plugin.

WPForms is the best WordPress form builder plugin on the market. It allows you to easily create Ajax powered forms aswell.

Upon activation, you need to visit WPForms » Settings page to enter your license key.

WPForms license key

After entering the license key, you’ll be able to receive automatic updates and install add-ons.

You are now all set up to make beautiful ajax forms in WordPress.

2. Create Your First Form

Let’s go ahead and create your first form.

Simply visit WPForms » Add New page in WordPress admin area. You’ll be asked to provide a title for your form and select a template as a starting point.

Choose form template

For the sake of this tutorial, we will be creating a contact form. However you can create any other type of form you need.

WPForms will now load your form with basic fields already added to it. You can simply point and click on any form field to edit it.

Editing form fields in WPForms

You can also add any new form field from the left column by simply clicking on it. The new field will appear at the bottom of your form just above the submit button.

Click to add a new form field

You can easily drag and drop form fields to move them up and down in the form.

Once you are finished editing the form, you can move on to the next step.

3. Turn On Ajax Form Submission Feature

WPForms does not enable Ajax form submission by default. You will need to manually enable it for your form.

Simply switch to the Settings tab in the form builder and check the box next to ‘Enable AJAX form submission’ option.

Turn on Ajax form functionality

Checking the box will turn on the Ajax functionality for this form.

Now let’s set up what happens after the form submission.

First, switch to the ‘Confirmation’ tab under settings. This is where you inform your users that you have received their form submission.

Confirmation settings

WPForms allows you to do that in different ways. For example, you can redirect users to a URL, show them a specific page, or simply display a message on screen.

Since we have enabled Ajax functionality for the form, redirecting users to another page will defeat the purpose of creating an Ajax form.

You need to select the message option and edit the confirmation message. Feel free to use the formatting toolbar on the editor or add a link or two to tell users where to go next.

After that, you can set up how you would like to be notified about a form submission.

Switch to the Notifications tab in the form settings and configure notification email settings.

Form notification email settings

Once you are done, you can save your form and exit the form builder.

4. Add Your Ajax Enabled Form in WordPress

WPForms makes it super easy to add forms into your WordPress posts, pages, and sidebar widgets.

Simply edit the post or page where you want to add the form and insert the WPForms block to your content area.

Add WPForms block to WordPress post or page

After that, you need to select the form you just created from the block’s settings. WPForms will immediately load a live preview of the form in the content editor.

Select your form

You can now save or publish your content and then visit your website to test the form’s ajax functionality.

Ajax contact form preview

You can also add your form to a sidebar widget in WordPress. To do that, go to Appearance » Widgets page and add the WPForms widget to a sidebar.

Add your ajax powered form to a sidebar widget

Select the form you created earlier and click on the Save button to store widget settings. You can now visit your website to see your Ajax powered form in action.

We hope this article helped you learn how to create a WordPress Ajax contact form for your website. You may also want to see our guide on how to create a contact form popup in WordPress.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Build a WordPress AJAX Form (in 4 Easy Steps) appeared first on WPBeginner.

Other Ways to SPAs

That rhymed lolz.

I mentioned on a podcast the other day that I sorta think WordPress should ship with Turbolinks. It's a rather simple premise:

  1. Build a server-rendered site.
  2. Turbolinks intercepts clicks on same-origin links.
  3. It uses AJAX for the HTML of the new page and replaces the current page with the new one.

In other words, turning a server-rendered app into "Single Page App" (SPA) by way of adding this library.

Why bother? It can be a little quicker. Full page refreshes can feel slow compared to an SPA. Turbolinks is kinda "old" technology, but it's still perfectly useful. In fact, Starr Horne recently wrote a great blog post about migrating to it at Honeybadger:

Honeybadger isn't a single page app, and it probably won't ever be. SPAs just don't make sense for our technical requirements. Take a look:

  • Our app is mostly about displaying pages of static information.
  • We crunch a lot of data to generate a single error report page.
  • We have a very small team of four developers, and so we want to keep our codebase as small and simple as possible.

... There's an approach we've been using for years that lets us have our cake and eat it too ... and its big idea is that you can get SPA-like speed without all the JavaScript.

That's what I mean about WordPress. It's very good that it's server-rendered by default, but it could also benefit from SPA stuff with a simple approach like Turbolinks. You could always add it on your own though.

Just leaving your server-rendered site isn't a terrible thing. If you keep the pages light and resources cached, you're probably fine.

Chrome has started some new ideas:

I don't doubt this server-rendered but enhance-into-SPA is what has helped popularize approaches like Next and Gatsby.

I don't want to discount the power of a "real" SPA approach. The network is the main offender for slow websites, so if an app is architected to shoot across relatively tiny bits of data (rather relatively heavy huge chunks of HTML) and then calculate the smallest amount of the DOM it can re-render and do that, then that's pretty awesome. Well, that is, until the bottleneck becomes JavaScript itself.

It's just unfortunate that an SPA approach is often done at the cost of doing no server-side rendering at all. And similarly unfortunate is that the cost of "hydrating" a server-rendered app to become an SPA comes at the cost of tying up the main thread in JavaScript.

Damned if you do. Damned if you don't.

Fortunately, there is a spectrum of rendering choices for choosing an appropriate architecture.

The post Other Ways to SPAs appeared first on CSS-Tricks.

WebSockets vs. Long Polling

Sometimes we need information from our servers as soon as it’s available. The usual AJAX request/response we’re all used to doesn’t keep the connection open for this sort of use case. Instead, we need a push-based method like WebSockets, long polling, server-sent events (SSE), or, the more recently created, HTTP2 push. In this article, we compare two methods: WebSockets and long polling.

An Overview of Long Polling

In 1995, Netscape Communications hired Brendan Eich to implement scripting capabilities in Netscape Navigator and, over a ten-day period, the JavaScript language was born. Its capabilities as a language were initially very limited compared to modern-day JavaScript, and its ability to interact with the browser’s document object model (DOM) was even more limited. JavaScript was mostly useful for providing limited enhancements to enrich document consumption capabilities. For example, in-browser form validation and lightweight insertion of dynamic HTML into an existing document.