Created
December 19, 2016 02:42
-
-
Save matthew-macgregor/2f11c5374984227d94f17a7ac30640d7 to your computer and use it in GitHub Desktop.
A couple of quick WP-Ajax examples.
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 | |
/* | |
Plugin Name: Ajax Demo | |
Plugin URI: | |
Description: Yes, this is an ajaxy plugin. | |
Author: Matsuzine | |
Version: 1.0 | |
Author URI: | |
*/ | |
add_action( 'plugins_loaded', 'up_initialize_plugin' ); | |
function up_initialize_plugin() { | |
new Admin_Ajaxy(); | |
} | |
class Admin_Ajaxy { | |
public function __construct() { | |
add_action( 'wp_ajax_add_foobar', array( $this, 'receive_ajax' )); | |
add_action( 'admin_footer', array($this, 'inject_javascript')); | |
} | |
public function receive_ajax() { | |
// Don't forget to stop execution afterward. | |
$whatever = intval( $_POST['whatever'] ); | |
$whatever += 10; | |
wp_send_json(array( 'whatever' => $whatever)); | |
wp_die(); | |
} | |
function inject_javascript() { | |
// Obviously hardcoded image id... | |
$img = 4; | |
$nonce = wp_create_nonce('image_editor-' . $img); | |
?> | |
<script type="text/javascript" > | |
jQuery(document).ready(function($) { | |
var data = { | |
'action': 'add_foobar', | |
'whatever': 1234 | |
}; | |
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php | |
jQuery.post(ajaxurl, data, function(response) { | |
console.log('Got this from the server: ', response); | |
}); | |
// an example of calling one of the core ajax methods... | |
jQuery.post(ajaxurl, { 'action': 'image-editor', 'postid' : 4, '_wpnonce' : '<?php echo $nonce?>' }, function(response) { | |
console.log(response); | |
}); | |
}); | |
</script> | |
<?php | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment