February 16 2016

WordPress Ajax Example

Tagged Under : , ,

Wordpress
Below is the basic example of how to use AJAX in WordPress. It show you how to using javascript pass the variable to PHP function and then return back to javascript.

Javascript
var ajaxurl = '<?php echo admin_url() ?>admin-ajax.php';
jQuery(document).ready(function () {
	jQuery.ajax({
		url: ajaxurl,
		data: {
			//This action must same with the PHP function name
			"action": "ajax_request",
			"params": "wordpress ajax"
		},
		success:function(data) {
			//This is the result return from PHP function
			console.log(data);
		},
		error: function(errorThrown){
			//This is the error return
			console.log(errorThrown);
		}
	});
});
PHP function
This PHP function you can put inside the Theme functions.php file. Or if you are using plugin, you can put inside the plugin file as well.
function ajax_request() {
	$params = $_GET['params'];
	
	if ($params == "wordpress ajax") {
		echo "is wordpress";
	} else {
		echo "Not wordpress";
	}

	die();
}
After that remember define the function with “wp_ajax_xxxxx” and “wp_ajax_nopriv_xxxxx”. xxxxx is the function name.
add_action('wp_ajax_nopriv_ajax_request', 'ajax_request');
add_action('wp_ajax_ajax_request', 'ajax_request');
If you the wordpress ajax return 0 to you. it was because fail to call the function. Make sure the action name you call same with the PHP function name.

Make a Comment

You must be logged in to post a comment.