[wp-hackers] ajax and $wpdb

Jess Planck jess at funroe.net
Wed Jul 29 18:00:25 UTC 2009


That sure does beat doing a template_redirect or trying to point to  
some custom php thing in a plugin or theme url "http://nasty-something/ 
wp-content/where??/".

It is worthwhile to note that the _nopriv_ will only run for logged  
out visitors. For some cases you may need to perform ajax for  
authenticated visitors as well.

If the intertubes don't mangle it, this is a small experiment added to  
a theme's function.php where the theme had a proper wp_footer() call  
and I just threw the jquery enqueue into init:

function my_jquery_enqueue() {
	wp_enqueue_script( 'jquery' );
}
add_action( 'init', 'my_jquery_enqueue' );

function my_ajax_handler() {
	var_export( $_POST );
}

if ( defined( 'DOING_AJAX' ) ) {
	if ( is_user_logged_in() )
		add_action('wp_ajax_my_action', 'my_ajax_handler');
	else
		add_action('wp_ajax_nopriv_my_action', 'my_ajax_handler');
}

function my_ajax_handler_js() {
?>

	<div id="wp-ajax-debug">Ajax Debug</div>
	
	<script type="text/javascript" charset="utf-8">
	/* <![CDATA[ */	
	
	jQuery.post(
		'<?php echo admin_url('admin-ajax.php'); ?>',
		{
			action: 'my_action',
			foo: 'bar'
		},
		function( data ) {
			jQuery( '#wp-ajax-debug' ).html( '::DONE:: ' + data );
		}
	);
	
	/* ]]> */
	</script>

<?php
}
add_action( 'wp_footer', 'my_ajax_handler_js' );

Have fun, I am!

Jess

[  :P  ]  jess planck  -  http://funroe.net

On Jul 29, 2009, at 9:54 AM, Otto wrote:

> The nopriv stuff got added 5 months ago, here:
> http://core.trac.wordpress.org/changeset/10720



More information about the wp-hackers mailing list