Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
    
Did you try and search it in the community? –  Maruti Mohanty Dec 11 '13 at 11:36
1  
Can you post the metabox code this goes with? –  helgatheviking Dec 11 '13 at 12:06
    
@helgatheviking I've updated the post with the meta box. –  Christiaan Dec 11 '13 at 13:17
    
@MarutiMohanty I did search, but didn't find anything that appeared to address my situation. –  Christiaan Dec 11 '13 at 13:17
    
Well, I'm still stumped on the encode/decode, but for sure you need to change $authordata['display_name'] to $authordata->display_name as $authordata is an object and not an array. –  helgatheviking Dec 11 '13 at 15:28

2 Answers 2

Your action hook should be

add_action( 'wp_ajax_cc_author_change_postauthor', 'cc_author_change_postauthor_callback' );

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

cc-author-change-postauthor

to

cc_author_change_postauthor
share|improve this answer
    
I tried your suggestion, but it didn't make a difference. It should work how I had it, as long as I make sure to use the same name in the 'action' key in my JS file. –  Christiaan Dec 11 '13 at 13:19
    
@Christiaan have been working with Ajax for the last few months and i got the same problem several times. It always ended up with the callback function. If your callback function is not invoked you cannot return any data. I assume you are not using the above code in the front-end. If yes, use 'wp_ajax_nopriv' hook. –  sri Dec 11 '13 at 13:45
    
@Christiaan updated my answer. I'm most certain this should work. –  sri Dec 11 '13 at 14:06
    
Christiaan's hook is correct. I can get it to fire. The problem is somewhere in the response. –  helgatheviking Dec 11 '13 at 15:27
1  
If he's actually getting back a "zero", then his hook is not being called. That's the default response. If his hook was called and he exit's as it shows in that function, then he could not get back a zero. The last line in admin-ajax.php is die( '0' );, which is where that comes from. –  Otto Dec 11 '13 at 17:11

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!

share|improve this answer
    
then please accept your answer for the question. If possible, please give a bit more detailed explanation. Thanks. –  sri Dec 12 '13 at 8:48
    
It's making me wait until tomorrow to accept my answer. I'll add some code to my explanation. –  Christiaan Dec 12 '13 at 15:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.