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.
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.
Share Improve this question edited Nov 16, 2020 at 8:14 Raashid Din asked Nov 16, 2020 at 6:19 Raashid DinRaashid Din 2182 silver badges19 bronze badges2 Answers
Reset to default 2The 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.
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/AJAX_in_Plugins