KB Knowledge Base
How To Process AJAX Request On WordPress - Part 2

Article By khan


img

Introduction to AJAX

Hello everyone, I’m back again. In my previous tutorial we looked at AJAX request processing. Now we’ll learn how to implement it with plugin development.

wordpress ajax tutorial

In this tutorial we are going to make a plugin which will take an integer number as an input and then it will show the amount of posts from WordPress.

The Skeleton

First thing first. We need to make the plugin skeleton with the help of our previous tutorial. Here it is.

/*
Plugin Name: Test AJAX
Plugin URI: https://rnaby.github.io
Description: A WordPress plugin to test AJAX request. It's developed as a part of BIPMedia.com tutorial.
Version: 1.0.0
Author: Khan Mohammad Rashedun-Naby
Author URI: http://bd.linkedin.com/in/rnaby
License: GPL V3
*/

This piece of code explains some vital information about the plugin we are going to develop. I think it is quite self explanatory, so please read it carefully.

Now for the second part. Here we are going to register a JavaScript file which will hold the AJAX script. If you find it difficult to understand please read my previous tutorial.

// Second Part, Enqueuing AJAX script file.
function rnaby_call_ajax_scripts() {
    // WP call scripts
    wp_enqueue_script( 'rnaby_ajax_js', plugin_dir_url( __FILE__ ) . 'js/ajaxscript.js', array( 'jquery' ), '1.0.0', true );

    // Localization for Ajax.
    wp_localize_script( 'rnaby_ajax_js', 'WpAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'init', 'rnaby_call_ajax_scripts' );

Here it the third part. Here we are going to call the PHP function through AJAX. In my previous tutorial I described it broadly, so if you have any issues with understanding this part please check the first part of the tutorial.

// Third Part, PHP function which is called by AJAX.
function rnaby_fetch_data(){
    $postcount = $_POST["postcount"];
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $postcount,
        'order' => 'ASC'
    );
    $results = get_posts( $args );
    $postnum = 0;
    foreach ($results as $key => $result) {
        $postnum++;
        echo '

' . $postnum . '.' . $result->post_title . '

'; echo '

' . $result->post_content . '

'; } die(); } add_action( 'wp_ajax_rnaby_fetch_data', 'rnaby_fetch_data' ); add_action( 'wp_ajax_nopriv_rnaby_fetch_data', 'rnaby_fetch_data' );

In the fourth part we've written a function which is called by a shortcode. If the shortcode concept is new for you please do a quick search so you are up to speed.

// Fourth Part, Shortcode Function.
function rnaby_get_input() { ?>
     

Enter Post Number:


Here is the fifth part, in which we’ll see the AJAX file and see the skeleton we built in the previous tutorial.
jQuery(document).ready(function($) {
	jQuery('#text-button').click(function(event) {
		/* Act on the event */
		jQuery.ajax({
			url: WpAjax.ajaxurl,
			type:'POST',

data:{ action : 'rnaby_fetch_data', postcount: jQuery('#post-count').val() }, beforeSend: function(){ jQuery('#text-button').attr('disabled', true); jQuery('#post-count').attr('disabled', true); }, success:function(response){ jQuery('#text-button').attr('disabled', false); jQuery('#post-count').attr('disabled', false); }, }).done(function( response ) { jQuery( "#results" ).html( response ); }); }); });
Now lastly, we need to define the file structure, so here we go. Please keep these file as they are shown here.
test-ajax
    |
    +---js/ajaxscript.js
    |
    +---test-ajax.php



How it is all going to work?

We are now ready to put all the parts in one PHP file and I’m also going to explain how the plugin is going to work.

Firstly the AJAX script will be enqueued to the system and run where we place the shortcode [rnaby_test_ajax]. This shortcode is going to generate a input box, a input box label and a button. When you input a number in the box and hit the button it will show you that number of posts.

The AJAX file is monitoring the button with the .click() function to see if it's clicked or not. When the button is clicked it fires the function inside itself. The function gets the input with postcount: jQuery('#post-count').val() and passes the variable to the PHP function rnaby_fetch_data(). Then the PHP function fetches the post. Lastly the jQuery function .done() gets the data and merges it to the frontend.


Conclusion

In this tutorial you've seen how to use the AJAX request processing with a WordPress plugin. I hope you found this tutorial helpful. I've also uploaded this plugin to GitHub. You can download it if you want. If you have any question please feel free to leave a message below and I will reply just as soon as I can.




Tags: , , , , , , , ,

Spin up a VPS server in no time flat

Simple setup. Full root access. Straightforward pricing.

DEPLOY VPS SERVER

Leave a Reply



Feedbacks