How to : A better way to fetch data via AJAX in WordPress 7 comments

I have released an article a while ago to do the AJAX thingy. However, there is another way, which is somewhat better, to fetch data via AJAX and it is easy to implement it.

First, I declare the javascript variables inside header.php:

var ajaxurl = '<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php';
var nonce = "<?php echo js_escape( wp_create_nonce( 'example-ajax-nonce' ) ); ?>";

Then, I’m using an external javascript file and you may name it anything, in this example, I’ll name it main.js:

// your form id
var form = $("#theForm");

// bind form here
form.bind("submit", function(e) {
	// serialize the input data
	var data = $(this).serialize();

	// make AJAX request
	$.ajax({
		url:		ajaxurl,
		type:		'post',
		dataType: 	'json',
		cache:		false,
		data:		{ "action":"<YOUR_ACTION_NAME>", "a":"your-case", "nonce": nonce, "data": data },
		beforeSend:	function(){
			alert('Sending...');
		},
		success:	function(obj){
			if( obj.response == 'success' ) {
				// success
			}
			else if( obj.response == 'failed' ) {
				// failed
			}
		}
	});

	// prevent form from submitting
	e.preventDefault();
});

For your process file, you can name it whatever you want, in this example, I’ll name it process.php:

$a = $_POST['a'];

switch($a) {
	// return result in json format
	case 'your-case': header("Content-type: application/json");

		//
		// create your process here
		//

		echo json_encode( array('response'=>'success', 'message'=>'Successfully cleared') );

	break;
}

Open up your functions.php file and add this function:

function YOUR_FUNCTION_NAME() {
	$nonce = $_POST['nonce'];

	// check to see if the submitted nonce matches with the
	// generated nonce we created earlier
	if ( ! wp_verify_nonce( $nonce, 'example-ajax-nonce' ) ) {
		header("Content-type: application/json");

		echo json_encode(
			array('response' => 'failed', 'message' => 'Verify nonce failed!')
		);

		exit;
	}

	// permission allow to Super Admin and Admin only
	if ( current_user_can( 'activate_plugins' ) ) {
		// path to your process file
		include TEMPLATEPATH . '/ajax_process.php';
	}
	else {
		header("Content-type: application/json");
		echo json_encode(
			array('response' => 'failed', 'message' => 'Insufficient permissions!')
		);
	}

	exit;
}

As for the logged in user, say like, for your theme options panel use:

add_action('wp_ajax_<YOUR_ACTION_NAME>', 'YOUR_FUNCTION_NAME');

If you plan to use AJAX on the front end, add this line and create another function similar to above but without checking permission:

add_action('wp_ajax_nopriv_<YOUR_ACTION_NAME>', 'YOUR_FUNCTION_NAME');

Take note that you must provide both action calls to make sure it all gets processed.

That’s all folks! You’ve successfully spice up your theme with AJAX. Have a nice day ツ.

Stay tuned for more news and follow us on Twitter and Facebook. Also subscribe to our Feeds and have the updates mailed to your mailbox.

wave spacer
spacer

Get Updates From Us!

 

Tasty News Straight to Your Mailbox

spacer