3

I am trying to set up some custom front-end user profile functionality and I'm using AJAX to allow users to edit their profile. This is my first time setting up AJAX on WP, and I feel like I'm so close! I checked a lot of other forums, and I couldn't seem to get past where I am now. Any advice would help!

I have a child theme set up with a user-profile template set up with a form. Then I have a js file to handle the AJAX with jQuery. Then I enqueued and localized my script in the functions.php as well as have a callback action set up in the functions.php. I think there is something off with my callback. I have the code pasted below.

FORM:

<form id="user-profile-frontend">

    <label>
        <span>Email:</span>
        <input type="text" name="email" id="email-val" value="<?php echo $current_user->user_email ?>" />
    </label>

    <label>
        <span>First Name:</span>
        <input type="text" name="first-name" id="first-name" value="<?php echo $current_user->user_firstname ?>" />
    </label>

    <label>
        <span>Last Name:</span>
        <input type="text" name="last-name" id="last-name" value="<?php echo $current_user->user_lastname ?>" />
    </label>

    <label>
        <span>Display Name:</span>
        <input type="text" name="display-name" id="display-name" value="<?php echo $current_user->display_name ?>" />
    </label>

    <input type="submit" value="Update Profile" />
</form>

jQuery AJAX JavaScript file

jQuery('document').ready(function(){

    jQuery('#user-profile-frontend').submit(function(e){

        e.preventDefault();

        var user_meta_val = jQuery( '#first-name' ).val();
        var user_meta_key = jQuery( '#first-name' ).attr('id');

        if ( jQuery('user_meta_val') ) {
            jQuery.ajax ({
                url: user_meta_ajax.ajaxurl,
                type: 'POST',
                data: {
                    action: 'user_meta_callback',
                    'user_meta_val': user_meta_val,
                    'user_meta_key': user_meta_key
                }
            })
            .success( function(results) {
                console.log( 'User Meta Updated' );
            })
            .fail ( function(data) {
                console.log( data.responseText );
                console.log( 'Request Failed' + data.statusText );
            })
        } else {
            console.log( 'Uh oh. User error message' );
        }

        return false;
    });

});

functions.php actions

function user_profile_enqueue() {

    // Register script for localization
    wp_register_script ( 
        'user-profile-mod',
        get_stylesheet_directory_uri() . '/js/user-profile-mod.js',
        array( 'jquery' ),
        '1.0',
        true
    );

    // Localize script so we can use $ajax_url
    wp_localize_script (
        'user-profile-mod',
        'user_meta_ajax',
        array(
            'ajaxurl'   => admin_url( 'admin-ajax.php' )
        )
    );

    // Enqueue script
    wp_enqueue_script( 'user-profile-mod' );
}
add_action( 'wp_enqueue_scripts', 'user_profile_enqueue' );

function user_meta_callback() {

    if ( !isset( $_POST) || empty($_POST) || !is_user_logged_in() ) {
        header( 'HTTP/1.1 400 Empty POST Values' );
        echo 'Could not verify POST values';
        exit;
    }

    $user_id = get_current_user_id();
    $user_meta_key = sanitize_text_field( $_POST['user_meta_key'] );
    $user_meta_val = sanitize_text_field( $_POST['user_meta_val'] );

    // Update single meta value
    update_user_meta( $user_id, $user_meta_key, $user_meta_val );

    // if (is_wp_error($user_id)) {
    //    echo $user_id->get_error_message();
    // }
    // else {
    //    echo 'Field updated!';
    // }

    exit;
}
add_action( 'wp_ajax_user_meta_callback', 'user_meta_callback' );
add_action( 'wp_ajax_nopriv_user_meta_callback', 'user_meta_callback' );

Right now I am just trying to get it to work with one, then I'll use wp_update_user to update the user object on submit.

What I have done so far to try and diagnose the problem: Chrome Console isn't giving any JS errors. When I submit the form I get the success message from the jQuery saying "User Meta Updated" but I refresh the page and/or check the profile from the dashboard and the data has not changed.

The dev site is hosted on WP Engine and using the log for debugging on their end, I have no errors at this point. The only error I had was from handling the is_wp_error so I just have it commented out. I'm not focused on that right now.

I don't think it's hitting the callback function.

Thank you in advance.

  • 1
    So what's happening? What's the issue - is it even hitting the ajax callback? Have you checked your debug log to see if there's any JS errors? How about debug.log for any PHP errors? Please edit your question using the edit button above and add in some additional information on what exactly is wrong and what you've tried to solve the issue. – Howdy_McGee Jul 26 '17 at 17:00
  • Thank you for the response! I edited my question above with some comments near the bottom explaining the steps I have taken so far to target the problem. – Dylan Wagner Jul 26 '17 at 17:24
  • 1
    How do you know if it succeeded? it only outputs something if it fails, also, have you considered using the REST API instead? Much easier to secure, far less error prone. Also that could be used to set any user meta, including additional ones, and ones from other plugins or core, it could be dangerous – Tom J Nowell Jul 26 '17 at 18:09
  • Well actually it is set to console.log on success as well.. I haven't considered the REST API. I don't have any experience working with it. – Dylan Wagner Jul 26 '17 at 18:18
1

This whole thing works as far as I can tell. In the future it may be easier to debug things by using PHP error_log() to write to the debug.log at certain points, like inside your ajax callback.

If you're only wanting to run this ajax for logged in users, you can drop the wp_ajax_nopriv hook and the is_user_logged_in() conditional and just stick with wp_ajax_* hook. wp_ajax_nopriv is "No Privileges" which means it will run for non-logged in users. The normal wp_ajax function will only run for logged in users.

The main issue is that your keys do not match the WordPress usermeta keys. You're grabbing the inputs ID which is first-name but WordPress expects first_name as the metakey. I bet if you checked your databases uusermeta table, you'd see a couple instances of first-name as a metakey.

  • 1
    That worked. I can't believe it was something so simple. Thanks! – Dylan Wagner Jul 26 '17 at 18:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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