bueltge
9/26/2011 - 2:30 PM

How to use AJAX with WordPress to post and process Javascript

How to use AJAX with WordPress to post and process Javascript

<?php
/*
 * Example of how to use AJAX with WordPress to post and process Javascript arrays of objects.
 * Drop this in your WordPress theme's functions.php file and it will display the array of objects on page load in the admin
 * REF: http://lists.automattic.com/pipermail/wp-hackers/2011-September/040834.html
 * By: Mike Schinkel - http://about.me/mikeschinkel
 */
add_action( 'admin_init', 'mytheme_admin_init' );
function mytheme_admin_init() {
	wp_enqueue_script('jquery');
}
add_action( 'wp_ajax_my_action', 'mytheme_wp_ajax_my_action' );
function mytheme_wp_ajax_my_action() {
	print_r($_POST['object']);
	die();
}

add_action( 'admin_head', 'mytheme_admin_head' );
function mytheme_admin_head() {?>
<script type="text/javascript">
jQuery(document).ready(function($) {
	// This is the Dashboard icon in the admin
	var data = {
		action: 'my_action',
		object: [
			{link:"Test 1",title:"Test 1",text:"Test 1",image_url:""},
			{link:"Test 2",title:"Test 2",text:"Test 2",image_url:""},
			{link:"Test 3",title:"Test 3",text:"Test 3",image_url:""},
			{link:"Test 4",title:"Test 4",text:"Test 4",image_url:""}
		]
	};
	jQuery.post(ajaxurl, data, function(response) {
		alert('Got this from the server: ' + response);
	});
});
</script>
<?php
}