How to get data via AJAX in WordPress

Adding AJAX function to your WordPress like Loading more posts button will be more user friendly. Following are the simple way to call AJAX in a WordPress plugin.

HTML

When this button is clicked, it sends AJAX request to our defined URL, which is admin-ajax.php in this case.

<form>
<button class="ajax_button" name="submit" data-author="TLTemplates">Post AJAX</button>
</form>

Plugin’s PHP file

We use wp_ajax_nopriv_[action_name] and wp_ajax_nopriv_[action_name] actions to define a function which handles AJAX request. The former is for logged-in users while the later is for guests.

In the plugin file, we need to enqueue JavaScript file and use wp_localize_script to register ajax URL.

function myplugin_scripts() {
    wp_enqueue_script('myplugin-js', plugin_dir_url(__DIR__). '/my-plugin.js', array('jquery'), time() ); 
	wp_localize_script(
	   'myplugin-js',
	   'ajax_obj',
	    array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))
	);
}

add_action('wp_ajax_nopriv_myaction', 'myaction_callback');
add_action('wp_ajax_myaction', 'myaction_callback');
function myaction_callback(){
	$author = $_POST['author'];
	echo 'Author: '.$author;
	wp_die();
}

my-plugin.js

jQuery(document).ready(function(){
    jQuery('.ajax_button').on('click', function(){    	
		var data = {
		  action: 'myaction',
		  author: jQuery(this).attr('data-author')
		};
		jQuery.post( ajax_obj.ajaxurl, data, function( response ) {
		  	console.log( response );
		});		
	});        
});

Here is the result we will see in the console after clicking on Post AJAX button.

Leave a Comment

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


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close