How To Create WordPress Plugin With Ajax

Ajax is the acronym for Asynchronous JavaScript And XML. It’s very usefull if you want to reload specify information from web server. It purpose to reload part of data on the web , so we don’t need to reload all website

To use ajax in WordPress , you need to know PHP and jQuery. Here is some wordpress api which you need to know to use ajax in wordpress :

  • add_action with wp_enqueue_scripts , wp_ajax_your_variable, wp_ajax_nopriv_your_variable
  • wp_create_nonce
  • wp_localize_script : to create variable which needed in javascript
  • check_ajax_referrer : check if referrer from same server
  • wp_die

Here is zz-ajax.php code :

<?php
/*
Plugin Name: ZZ Ajax
Plugin URI: http://www.wpamanuke.com
Description: Sample Ajax
Version: 1.0.1
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/

add_action( 'wp_enqueue_scripts', 'zz_ajax_enqueue_scripts' );
function zz_ajax_enqueue_scripts() {
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'zz-ajax-script', plugins_url( '/test-ajax.js', __FILE__ ), array('jquery') , '1.0', true);
		
	$nonce = wp_create_nonce( 'zz_ajax_nonce' );
	wp_localize_script( 'zz-ajax-script', 'zz_ajax_var', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) , 'nonce' => $nonce ) );
	
}

add_action( 'wp_ajax_zz_ajax_action', 'zz_ajax_action' );
add_action( 'wp_ajax_nopriv_zz_ajax_action', 'zz_ajax_action' );
function zz_ajax_action() {
	check_ajax_referer( 'zz_ajax_nonce' , '_ajax_nonce' );
	echo "This is ajax message 1234";
	wp_die(); // this is required to terminate immediately and return a proper response
}

test-ajax.js code

jQuery(document).ready(function($) {
	
	var data = {
		'_ajax_nonce': zz_ajax_var.nonce,
		'action': 'zz_ajax_action'
	};
	
	jQuery.post(zz_ajax_var.ajax_url, data, function(response) {
		alert('Got this from the server: ' + response);
	});
	
});

Leave a Reply

Your email address will not be published. Required fields are marked *