1

Will someone guide why this code doesn't work. Even the data gets changed. Here is the ajax I use.

jQuery(document).ready(function($) {
    $(".ue_ajax_enabled").on('click', function(event) {
        event.preventDefault();
        /* Act on the event */
        $.ajax({
            url:  ue_ajax.ajax_url,
            type: 'POST',
            /*dataType: 'json',*/
            data: {
                'action'    : 'ue_ajax_enabled',
                'new_username'  : $("#new_username").val(),
                'nonce'     : $("#new_username_nonce_check").val(),
            },
            beforeSend: function () {
                $(".ue_ajax_enabled").text(ue_ajax.beforeMessage);
            },
            success: function (data) {
                console.log('Success');
                console.log(data);
            },
            error: function (data) {
                console.log('Error');
                console.log(data);
            }
        })
        
    });
});

Here is the ajax action hook I use.

    add_action( "wp_ajax_ue_ajax_enabled", 'ue_ajax_enabled' );
    
    function ue_ajax_enabled() {
    global $wpdb;

    $currentUser = wp_get_current_user();
    $user_id = $currentUser->ID;

    if (  is_user_logged_in() && wp_verify_nonce( $_REQUEST['nonce'], 'new_username_nonce' ) && ! empty($_REQUEST['new_username'])) {

        // Get name of our users table
        $tableName = $wpdb->prefix . 'users';

        if ( !username_exists( $_REQUEST['new_username'] ) ) {
            // Stripslashes and trim any whitespace, also replace whitespace with underscore
            $newUsername = trim(str_replace(' ', '_', stripslashes($_REQUEST['new_username'])));
        } else {
            echo json_encode( array('username' => 'Username exists, try any other') );
            die();
        }

        // Data to change
        $dataToChange = array('user_login' => $newUsername);

        // Where to Change
        $whereToChange = array('ID' => $user_id); 

        // Change the data inside the table
        $result = $wpdb->update($tableName, $dataToChange, $whereToChange, array('%s'), array('%d'));


        if ($result) {
            echo json_encode( array('update' => true) );
        } else {
            echo json_encode( array('update' => false) );
            die();
        }

        if (ue_send_email_to_user()) {
            $subject = 'Username Changed Successfully ID:' . $user_id;
            $message = "<p>You username has been successfully changed. Your new details are given below.</p>";
            $message .= "<strong>Previous Username:</strong><span>{$currentUser->user_login}</span>";
            $message .= "<strong>New Username</strong><span>{$newUsername}</span>";
            $from = "From: " . get_bloginfo('name');

            wp_mail( array(ue_get_administrators_email(), $currentUser->email), $subject, $message, $from );
        }
    }
    die();
}

The code throws an error message in the console instead of the success message of the ajax set earlier. Any clue why this happens. Thanks in advance

UPDATE: by commenting datatype the problem solves. But still it shows undefined when i access json.

2

The issue in your code is simple: if you want to send a JSON response, then make sure it's a valid JSON response, i.e. send the correct Content-Type header and a proper JSON-encoded body. With jQuery.ajax(), though, you can omit the header, but you'd need to set the dataType to json.

function my_ajax_callback1() {
    // Invalid JSON response.
    die();
}

function my_ajax_callback2() {
    // Good JSON response with a Content-Type header.

    header( 'Content-Type: application/json' );
    echo json_encode( array( 'update' => true ) );

    wp_die(); // die() works, but wp_die() is better
}

And actually, in your callback, you could simply use wp_send_json() like so:

function my_ajax_callback3() {
    wp_send_json( array( 'update' => true ) );
    // No need to call wp_die(), die() or exit().
}

And there also wp_send_json_success() and wp_send_json_error(), but in your JS, you would need to use data.data.<key> and not data.<key>, except for data.success.

function my_ajax_callback4() {
    // ... your code

    // In your success( data ) JS, you'd access the 'update' value via data.data.update

    if ( $result ) {
        wp_send_json_success( array( 'update' => true, 'msg' => 'Success!' ) );
    } else {
        wp_send_json_error( array( 'update' => false, 'msg' => 'Foo error' ) );
    }
}

So be sure to return a valid response data and although not required, I suggest you to consider creating a custom REST API endpoint for your custom AJAX action and point your AJAX requests to that API endpoint — which (by default) always returns a JSON response.

1
  • 1
    Thanks for your help. I mentioned that I solved the error. But your code is far better than my code. This is a nice answer. Thanks for teaching. – Raashid Din Nov 16 '20 at 11:52
2

I think you forgot an action of ajax in WP when submitting you not login. So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this:

add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );

and after return ajax, you must use die() function to respond to the return data.

Read more: https://codex.wordpress.org/AJAX_in_Plugins

5
  • I use it only for logged in users. – Raashid Din Nov 16 '20 at 7:44
  • In the die(); function, I don't see you return the message data after the success or fail process. – Quang Hoang Nov 16 '20 at 7:54
  • we don't need to send message in die() because i am already using json_encode(). – Raashid Din Nov 16 '20 at 7:56
  • The question solved by commenting datatype – Raashid Din Nov 16 '20 at 7:56
  • 1
    thanks for your help too. Keep supporting others – Raashid Din Nov 16 '20 at 11:54

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.