Language:

Search

Ajax your WordPress - The Efficient way

  • Share this:
Ajax your WordPress - The Efficient way

What's AJAX?

Ajax is a JavaScript based technology that allows a web page to fetch data from the server without refreshing the web page.

Ajax in WordPress

WordPress utilizes the AJAX functionality only in the admin screens by default. For example, while updating plugins & saving settings & configurations in the admin screens etc.

Using AJAX on the front-end - The WP way

WordPress makes use of the AJAX functionality in a more complex manner, that it takes some time to completely understand whats going on the inside of the hooks.

Firstly

If you want to fire AJAX on the front-end of your website, you need to add the following actions in your theme's functions.php

add_action( 'wp_ajax_my_action', 'my_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_callback' );

Secondly

Pass the ajaxurl to javaScript's context to make some use out of it.

In your header.php, place the following code:

<script>

var ajaxurl = '{{ site.link }}/wp-admin/admin-ajax.php'

</script>

The Efficient way

We at The Web Tier, always wanted to keep the theme's function.php clean & utilizes the Object Oriented approach for better development workflow. Same follows for the using the AJAX functionality with WordPress.

The directory structure

If you want to follow along, lets create a new PHP class "App/Helpers/Utils.php" inside your theme directory (I'm sure you'd understood that you need to create App & Helpers directories first).

<?php namespace App\Helpers;

class Utils 

{

/**
 * Add an action to admin-ajax.php
 *
 * @param $action
 * @param callable|\Closure $callback
 */

public static function ajax( $action, $callback )
 {

    add_action('wp_ajax_' . $action, $callback);

    add_action('wp_ajax_nopriv_' . $action, $callback);

 }

}

The Use Case

So, curious to know the use-case of this method? Below is the snippet

$app = new App\Helpers\Utils();
$app->ajax('my_form', 'your_callback_function()');

Simple enough?

Conclusion

If you came this long, try this method yourself & leave us a comment if you get stuck somewhere in between.

Usama Muneer

Usama Muneer

A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.