Following the directions here http://codex.wordpress.org/AJAX_in_Plugins#Ajax_on_the_Administration_Side
I wrote this code:
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.
Your url should be pointing to admin-ajax.php
This is how it should be done for your case, I went ahead and rewrote some things.
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
andjQuery.post
method to calladmin-ajax.php
and send thesendData
info to a function that will do some stuff with those variables, and then echo back aresponse
so you can do something with that as well.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.