Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
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.
Ajax is a JavaScript based technology that allows a web page to fetch data from the server without refreshing the web page.
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.
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>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.
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);
}
}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?
If you came this long, try this method yourself & leave us a comment if you get stuck somewhere in between.