I’m trying to get user profile values using an AJAX call, but the response is always 0. Here’s my PHP:
wp_enqueue_script( // Add JS to <head>
'cc-author-change-post-author',
plugins_url( 'assets/js/change-post-author.js', dirname( __FILE__ ) ),
'jquery'
);
wp_localize_script( // Localize script for AJAX calls
'cc-author-change-post-author', // Name of script call being localized
'authorchange', // AJAX object namespace, used to call values in the JS file
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ), // URL for admin AJAX calls
'nonce' => wp_create_nonce( 'cc-author-change-author-nonce' ) // Nonce to authenticate request
)
);
function cc_author_change_postauthor_callback() {
$nonce = $_POST['nonce']; // Assign a local variable for nonce
if ( ! wp_verify_nonce( $nonce, 'cc-author-change-author-nonce' ) ) { // If the nonce doesn't check out, fail the request
exit( 'Your request could not be authenticated' ); // Error message for unauthenticated request
}
if ( current_user_can( 'edit_others_posts' ) || current_user_can( 'edit_others_pages' ) ) { // Check for proper permissions before handling request
$author = $_POST['authorID']; // Assign local variable for submitted post author
if ( $author ) { // If an author ID was provided, get the user's details
$authordata = get_userdata( $author ); // Retrieve the selected user's data from their profile
$authormeta = json_encode( array( // Encode data as JSON
'display_name' => $authordata['display_name'], // Display name from profile
'description' => $authordata['description'] // Biographical info from profile
) );
}
else { // If no author ID was provided, send back an error message
$authormetaerror = 'No user ID provided. Please try again.'; // Error message to send back
$authormeta = json_encode( array( // Encode as JSON
'display_name' => $authormetaerror,
'description' => $authormetaerror
) );
}
echo $authormeta; // Return the values retrieved from the database
}
exit; // End response. Required for callback to return a proper result.
} // cc_author_change_postauthor_callback()
add_action( 'wp_ajax_cc_author_change_postauthor', 'cc_author_change_postauthor_callback' );
And here is my JavaScript:
jQuery( document ).ready( function( $ ) { // Don't execute anything until the page is loaded
$( "#cc_author_postauthor" ).change( function() { // If the author dropdown value is changed, execute the script
/* Data to pass to the server. Called below during $.post() */
var data = {
action : 'cc_author_change_postauthor', // Action hook for the server-side callback
nonce : authorchange.nonce, // Nonce received from server to authenticate request
authorID : $( "#cc_author_postauthor" ).val() // author ID for retrieving profile data
};
/* Send request to the server and process response */
$.post(
authorchange.ajaxurl, // URL to send the request to the server
data, // Data to send to the server, stored in var data
function( jsonString ) { // Script to execute upon successful response from server
var authormeta = $.parseJSON( jsonString ); // Parse the JSON received from the server response
$( "#cc_author_meta\[0\]\[display_name\]" ).val( authormeta.display_name ); // Change the value of the author display name to the value received from the server
$( "#cc_author_meta\[0\]\[description\]" ).val( authormeta.description ); // Change the value of the author bio to the value received from the server
} // function( jsonString )
); // $.post
}); // $( "#cc_author_postauthor" ).change()
});
Here’s the meta box where the form item is located:
function cc_author_metabox( $post ) {
/* Retrieve current values if they exist */
$cc_author_meta = get_post_meta( $post->ID, '_cc_author_meta', true ); // Author meta data (stored as an array)
$postauthorid = $post->post_author; // Get the user ID of the post author
/* If any of the values are missing from the post, retrieve them from the author's global profile */
if ( !$cc_author_meta ) {
$postauthor = get_userdata( $postauthorid ); // Retrieve the details of the post author
$cc_author_meta = array(); // Initialize main array
$cc_author_meta[0] = array( // Nested array for author data
'display_name' => $postauthor->display_name, // Set display name from post author's data
'description' => $postauthor->description // Set bio from the post author's data
);
}
/* Display the meta box contents */
?>
<div class="cc_author_metabox">
<p>Changes made to this information will only apply to this post, and will not be saved to the user's profile.</p>
<?php
if ( current_user_can( 'edit_others_posts' ) || current_user_can( 'edit_others_pages' ) ) { // Check the capabilities of the current user for sufficient privileges
wp_dropdown_users( array(
'name' => 'cc_author_postauthor', // Name for the form item
'id' => 'cc_author_postauthor', // Class for the form item
'selected' => $postauthorid // Select the post's author to be displayed by default
) );
?>
<noscript>
You have JavaScript disabled. If you change the post author in the dropdown, you will need to save the post for the fields below to update. Please enable JavaScript for a better experience.
</noscript>
<div id="cc_author_postauthor_loading" class="cc_author_postauthor_loading"><img id="cc_author_postauthor_loading_img" class="cc_author_postauthor_loading_img" src="<?php echo plugins_url( 'assets/img/loading.gif', dirname( __FILE__ ) ); ?>" width="20px" style="width: 20px;"></div>
<input type="hidden" name="cc_author_currentpostauthor" value="<?php echo $postauthorid; ?>">
<?php
}
?>
<label for="cc_author_meta[0][display_name]" class="selectit">Name</label>
<input type="text" name="cc_author_meta[0][display_name]" id="cc_author_meta[0][display_name]" value="<?php echo esc_attr( $cc_author_meta[0]['display_name'] ); ?>" />
<label for="cc_author_meta[0][description]" class="selectit">Bio</label>
<?
$descEditor = new ccAuthorDescEditor( $cc_author_meta[0]['description'], 'cc_author_meta[0][description]' ); // Create the bio editor object
echo $descEditor->editor(); // Display the editor
?>
</div>
<?php
}
I’m sure the answer is right in front of me, but this is my first time using the WordPress AJAX API. What am I doing wrong?
You can see the entire plugin code at its Github repository.
Your action hook should be
I think because of your wrong hook, your callback function is never called.
You might have got this wrong aswell. In your JS code please change your action from
to
I solved the problem. I was conditionally including the file where my PHP code was only if the REQUEST URI was one of the ones for editing a page or post. As such, the PHP code was not included when a request came via admin-ajax.php. I corrected that and now I’m all set. Thanks for everyone’s help!
instead of
use
die()
orwp_die()
” functions. it should be fixed.