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.