How do I hook an Ajax request into a PHP callback?

Following the directions here http://codex.wordpress.org/AJAX_in_Plugins#Ajax_on_the_Administration_Side

I wrote this code:

Read More

EDITED TO INCLUDE DIE(), STILL NOT WORKING

function my_button() {
echo
"<script type = 'text/javascript'>
function ajaxRequest(){
    jQuery(document).ready(function(jQuery) {
        var sendData = {};
        sendData['action'] = 'my_action';
        sendData['external_id'] = '$postID';
        sendData['title'] = '$post_title';
        sendData['content'] = '$post_content';
        jQuery.ajax({
            type: 'POST',
            url: 'http://lvh.me:3000/s/wp',
            xhrFields: {
                withCredentials: true
            },
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            data: sendData,
            error: function(jqXHR){
                console.log(jqXHR.responseText);
            },
            success: function(data){
                window.open(data['link']);
            }
        });
    })
};
</script>
<input type='button' onclick='ajaxRequest()' value='Send' />";
}

add_action( 'dbx_post_sidebar', my_button);

add_action('wp_ajax_my_action', my_action_callback);

function my_action_callback() {
  global $wpdb; // this is how you get access to the database
  $api_key = $_POST['api_key'];
  $user = wp_get_current_user();
  $user_id = $user->ID;
  add_user_meta($user_id, 'my_api_key', $api_key);
  die();
}

I know that’s a ton of code, but I just can’t figure out where the error is.

Thanks a ton.

Related posts

Leave a Reply

3 comments

  1. EDIT: I found several problems with your method.

    This is how it should be done for your case, I went ahead and rewrote some things.

    function my_button() {
    echo
    "<script type = 'text/javascript'>
        jQuery( document ).ready( function() {
    
            jQuery('input.sendajax').click( function() {
    
                var sendData = {
                    action: 'my_action',
                    external_id = $postID,
                    title: '$post_title',
                    content: '$post_content'
                };
    
                jQuery.post( ajaxurl, sendData, function( response ) {
    
                    // You need to send some type of validation back
                    // Like a 'success' variable either true or false
                    // Stuff sent back is accessed through the 'response' variable, so to get the item sent back called 'success', you would use 'response.success'
    
                    if( response.success == true ) {
                        window.open(response.link);
                    } else {
                        console.log(response);
                    }
    
                });
    
            });
    
        })
    </script>
    <input class='sendajax' type='button' onclick='ajaxRequest()' value='Send' />";
    }
    
    add_action( 'admin_head', 'my_button');
    
    add_action('wp_ajax_my_action', 'my_action_callback');
    
    function my_action_callback() {
      global $wpdb; // this is how you get access to the database
      $api_key = $_POST['api_key'];
      $user = wp_get_current_user();
      $user_id = $user->ID;
      add_user_meta($user_id, 'my_api_key', $api_key);
    
      $response = array( 'success' => true, 'link' => 'this is a response var' ); // Stuff to send back to AJAX
      echo json_encode( $response );
    
      die(); // Needs this
    }
    

    If you read the Codex carefully, and compare your code to the code here, they are very different. You were trying to use a method most would deem appropriate but WP already can do these things for you (which I didn’t even realize until a couple days ago, so don’t feel bad!)

    What I did is use WP’s native ajaxurl and jQuery.post method to call admin-ajax.php and send the sendData info to a function that will do some stuff with those variables, and then echo back a response so you can do something with that as well.

  2. It looks like you need to break down what you are doing into two parts.

    1 / Query your external api, and then return your API key

    2 / Associate the API key with a user.

    So, I would first query your API via a standard ajax call, and then in the success handler of that first ajax call, run your internal wp admin-ajax call to associate the user with the API key.