How to Use AJAX in WordPress to Load Search Results

How to Use AJAX in WordPress to Load Search Results

AJAX is a very powerful and flexible tool that allows developers to create more streamlined applications. It can be used for a wide range of purposes such as loading content or verifying login credentials.

The main benefit of AJAX is that it is asynchronous, meaning the whole page doesn’t need to reload in order for it to receive new data.

WordPress is well-equipped for AJAX. It has a great mechanism for working with it, allowing you to implement AJAX functionality with little fuss.

In this article I’ll take you through the basics of AJAX and we’ll create a very simple extension that pulls in search results using AJAX in the default Twenty Fourteen theme.

What Is AJAX?

AJAX is actually not one technology, it is a mixture of programming languages you probably already know. AJAX is short for Asynchronous Javascript And XML. Javascript is used to send some data to the server, which spits back something in return in XML format.

XML is actually not necessary, JSON is frequently used instead. When JSON is used we sometimes refer to it as AJAJ instead of AJAX. In fact, since a simple string or HTML could be returned by the server, we don’t need to be restricted to XML or JSON at all. For the purposes of this article I will refer to AJAX regardless of the type of data we return.

How is AJAX Used?

Let’s look at a practical example without delving into code. Let’s say you’ve created a real estate website and you offer the opportunity for visitors to save a listing to view later. This functionality could be offered using a “Save For Later” button.

When a user clicks this button they are taken to a script which adds the listing to their later list, and they are redirected back to the page they were viewing. This means that the page needs to be loaded again. A real estate website could be very image-heavy and many images may not be cached, which would contribute to a longer loading time.

A much better solution would be the following: The user clicks the button and a little loading animation is shown on the button. The button then fades out, the text “Listing Saved” is shown in its place. While this is happening the user can continue to use the website as usual.

Under the hood the process is very similar in both cases. When the button is clicked the user is not taken anywhere, but using Javascript we make a request to a specific file, providing the listing ID. The file in question figures out who the current user is and using the provided listing ID adds it to their later list. Once this is done the script returns a value which is transported back to the Javascript function. Based on this we can manipulate the UI to show the user meaningful interaction messages.

Don’t worry if that seemed a bit complex! In practice the process is pretty easy, it just takes some getting used to.

Using AJAX in WordPress

AJAX is completely independent of frameworks such as WordPress. You could implement it any way you like. There is, however, built in support in WordPress for an AJAX workflow. You should follow this if you want your plugin or theme to pass muster.

Let’s look at a very simple example in three steps. We’ll go from a custom solution to using AJAX foundations in WordPress without actually using AJAX itself to a fully-fledged implementation. We’ll create a one-time button, which will be displayed if the user hasn’t clicked it yet, or it will show “already clicked” if the user has clicked it before.

Custom Implementation

Before we continue we need to figure out how we know if a user has clicked the button or not. If a user clicks the button we will create a clicked_link user meta with the value of “Yes.” Here’s a function which checks this for us:

Now we can create the user interface. The button will show up if the user hasn’t clicked it yet (it will only be visible to logged in users). If a user has clicked it, the text “Already clicked” will be displayed:

When a user clicks the button the page is re-loaded with the button_click query string. Based on this value we can use an action to set the user meta:

Note that this method is not recommended for a number of reasons but it serves as proof of concept. At this point the button will show up for logged in users who have not clicked it. When you click it you are re-directed to the same page. Well before the button is loaded the user meta is recorded and as a result the correct “Already clicked” text is shown.

AJAX Foundations Without AJAX

Let’s bring this example one step closer to an AJAX implementation. We can already utilize the functions WordPress offers without actually writing any Javascript. This involves routing our actions through admin-ajax.php. Let’s take a look at how the code for our button changes as a result:

The only change is in the button’s URL. It points to the admin-ajax.php file in the WordPress admin directory. Additionally, an action parameter is specified with the value of button_click. We can’t write functions to deal with our actions into this file since it is a WordPress core file. We can, however, use actions to tie them to these events.

In order to tie a function to an action in the admin-ajax.php file we need to use the wp_ajax_[action] or wp_ajax_nopriv_[action] hooks. The former is fired for logged in users only, the latter for logged out users only. This is already a great way to protect our scripts!

Note that I also re-wrote the user_clicked() function to facilitate the changes. We no longer need to check if the user is logged in since that is taken care of by the wp_ajax_button_click hook. We do need to redirect the user back to the previous page, though.

Full AJAX Implementation

Our full AJAX implementation will use the foundations we’ve built in the previous example. Let’s begin by writing some Javascript, which will handle the click event on the button.

We detect the button click and use the ajax() function to send a request to the admin-ajax.php file. We make sure that the request type is post and the action is given as well. Elements of the data object will be transported as members of the $_POST array. A success function is put into place, which will replace the button with the already clicked text if the response is “OK.”

Note that from the admin-ajax.php file’s point of view this request is much the same as when we sent our users to the file directly. The action is set and thus our hook from before will function in the same way.

This time we don’t need to redirect the user since they won’t leave the page in the first place. We do need to echo “OK,” which will be used by our success function and we need to die(). This is required because the admin-ajax.php file will echo “0” otherwise.

Once a user clicks a button everything is handled asynchronously. Users can continue to use the site while this action is taking place. The button will eventually (pretty quickly) be replaced by the clicked text. If the user re-loads the page they will not see the button again since they have already clicked it.

AJAX Implementation With Fallback

Our new AJAX method is awesome but will ultimately fail if a user doesn’t have Javascript enabled. To be fair, it will work, but it won’t redirect the user back to the page they were on since we echo “0” and then die. WordPress provides the DOING_AJAX constant, which we can use to determine if an AJAX request is happening. If it is we echo and die, if it isn’t then we redirect:

By using this method we can use the same functions and same workflow for handling situations where Javascript is enabled and situations when it isn’t.

Load Your Site’s Search Results With AJAX

Let’s modify the Twenty Fourteen theme to load search results using AJAX on the search page. The first step is to create a child theme. Take a look at our artist on how to Create WordPress Child Themes for more infomation.

Enqueueing Assets

Next, let’s enqueue the javascript file we will use to implement our Javascript functionality. Note that I will make sure that the script is only loaded on the search page. The reason for this is that the search page may have a different sidebar than the regular post list page. So when the user first searches, the search page will actually load. Once on the search page the results will be pulled in via AJAX.

I have used the wp_localize_script() function to make sure I have access to the location of our admin-ajax.php file. Previously, this could be retrieved from the URL of our button, but we have no way to grab it from the page here.

The wp_localize_script() function can be used to add language support to your scripts. It is also a great way to pass variables to it as well which is how I’ve used it here. This will allow us to use myAjax.ajaxurl to point to the correct URL in our Javascript.

I’ve also enqueued a CSS file. The minimal CSS code we’ll be using could very-well be added in the child theme’s stylesheet. I chose to enqueue a dedicated file simply to compartmentalize our assets, it makes it easier to create a plugin out of it in the end.

Intercepting Searches

The next step is to intercept searches, stop them in their tracks and pass the search query to our custom script, which will return the new results. Let’s set up the Javascript for that now:

I used the beforeSend event to add a loading class to the content element and to disable the input. This will give the user some feedback and make sure that multiple searches don’t lead to multiple requests being sent. Upon success the contents of the #content element is replaced with the new results.

The CSS we’ll use to handle loading is the following, which will fade the content and produce a nice loading overlay:

And here’s what it all looks like on the front-end:

Loading Posts With AJAX
Loading Posts With AJAX

The Server Side

Our action from our Javascript call was load_search_results. We’ll need to use this in the actions we’ll be creating. This time we’ll need to make sure that it runs for both logged in and logged out users so we’ll be using both wp_ajax and wp_ajax_nopriv.

We’ll create a custom WordPress query and use the exact same code found in search.php in Twenty Fourteen to return our results:

The result of this function is some HTML, which is created using functions native to WordPress and Twenty Fourteen. This ensures that we’ll get the correct format every time, even if there are no posts found.

Conclusion

From small UI improvements to larger scale performance increases, AJAX is a great addition to your WordPress toolkit. When you encounter it for the first time you may need to try it out to wrap your head around it, but it really is very simple. It’s the complexity which can be added by complex Javascript on the front-end and complex PHP on the server side, which sometimes makes it a bit more difficult, not AJAX itself.

If you’re interested in AJAX functionality I highly recommend browsing through the AJAX-related plugins available in the WordPress Plugin Repository. I also suggest reading the W3Schools AJAX Tutorial and the documentation for the jQuery Ajax Function.

If you’ve created something great using AJAX in WordPress or you feel that some aspects of WordPress would benefit a lot from adding some AJAX at them, let us know in the comments below.