[wp-hackers] ajax to call function in theme

Otto otto at ottodestruct.com
Thu Oct 29 20:02:52 UTC 2009


Let me guess: You put this server side code into some separate PHP
file somewhere, and now are calling that PHP file directly from your
AJAX call, yes?

I suggest you re-read that tutorial, because that's exactly what you
*don't* do, and the tutorial explains why.


Here's a short example. All this will be in one file.

function my_action_javascript( )
{
   var mysack = new sack(
       "<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php" );
  mysack.execute = 1;
  mysack.method = 'POST';
  mysack.setVar( "action", "my_special_action" );
  mysack.setVar( "whatever", '1234' );
  mysack.onError = function() { alert('error' )};
  mysack.runAJAX();
  return true;
}

add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');

function my_action_callback() {
  $whatever = $_POST['whatever'];
 // $whatever here will be 1234.. See?
}


Take special note of the javascript code which has an "action"
variable. Also take note that it is calling the admin-ajax.php file,
not some other file that you created. Then note that my_special_action
is part of the first parameter in the add_action call. These are all
significant.

-Otto
Sent from Memphis, TN, United States


On Thu, Oct 29, 2009 at 2:47 PM, Sharon Chambers <sharon at brewerradio.com> wrote:
> Realized that was a bit lacking...
> Here's my simple test code following the AJAX tutorial in the codex (http://codex.wordpress.org/AJAX_in_Plugins):
>
> <?php
> $vote = $_POST['vote'];
> $results_id = $_POST['results_div_id'];
>
> global $wpdb;
> $results = 'db prefix: '. $wpdb->prefix;
>
> die( "document.getElementById('$results_id').innerHTML = '$results'" );
> ?>
>
> The above produces empty string for prefix:  db prefix:
>
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>


More information about the wp-hackers mailing list