Created
September 26, 2011 14:30
-
-
Save bueltge/1242366 to your computer and use it in GitHub Desktop.
How to use AJAX with WordPress to post and process Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment