Invalid nonce at loading commets
-
The default encoding used by
.ajax()doesn’t always play well with PHP. Try includingdataType : 'json',in your.ajax()parameters.Another cause for nonce failure is a disconnect between the active user who created the nonce and the user that Ajax is running under. Browser cookie issues can cause this.
Thank you @bcworkz I solved the issue, it was related with other function. Now I can load comments in the admin panel and all CRUD functions, but when I tried to create a comment with an image from the frontend I have the same issue “Invalid nonce”. I checked out the console and there is an issue related with cookies. How can I fix it? register_cokies_nonce… The image should be added in the media library with the post meta _group_media_comment. I used the same class-groups-comments-ajax.php to create_comment.
JQMIGRATE: Migrate is installed, version 3.4.1
comments.js?ver=1.0.0:10 User ID: 1
comments.js?ver=1.0.0:12 Nonce del frontend: a30e22255c
comments.js?ver=1.0.0:13 Path: https://localhost/southamericantravelers.club/wp-json/
jquery.min.js?ver=3.7.1:2 POST https://localhost/southamericantravelers.club/wp-json/wp/v2/media 403 (Forbidden)[email protected]?ver=3.7.1:[email protected]?ver=3.7.1:2(anonymous)@jquery-migrate.min.js?ver=3.4.1:2e.<computed>@jquery-migrate.min.js?ver=3.4.1:2(anonymous)@media_upload.js?ver=1.0.0:[email protected]?ver=3.7.1:[email protected]?ver=3.7.1:2
media_upload.js?ver=1.0.0:92 Error al enviar el comentario con imagen:
- {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
- abort: ƒ (e)
- always: ƒ ()
- catch: ƒ (e)
- complete: ƒ ()
- done: ƒ ()
- error: ƒ ()
- fail: ƒ ()
- getAllResponseHeaders: ƒ ()
- getResponseHeader: ƒ (e)
- overrideMimeType: ƒ (e)
- pipe: ƒ ()
- progress: ƒ ()
- promise: ƒ (e)
- readyState: 4
- responseJSON: {code: ‘rest_cookie_invalid_nonce’, message: ‘Cookie check failed’, data: {…}}
- responseText: “{\”code\”:\”rest_cookie_invalid_nonce\”,\”message\”:\”Cookie check failed\”,\”data\”:{\”status\”:403}}”
- setRequestHeader: ƒ (e,t)
- state: ƒ ()
- status: 403
- statusCode: ƒ (e)
- statusText: “Forbidden”
- success: ƒ ()
- then: ƒ (t,n,r)
- Prototype: Object
(anonymous)@media_upload.js?ver=1.0.0:92await in (anonymous)[email protected]?ver=3.7.1:[email protected]?ver=3.7.1:2
jquery.min.js?ver=3.7.1:2 POST https://localhost/southamericantravelers.club/wp-json/wp/v2/media 403 (Forbidden)[email protected]?ver=3.7.1:[email protected]?ver=3.7.1:2(anonymous)@jquery-migrate.min.js?ver=3.4.1:2e.<computed>@jquery-migrate.min.js?ver=3.4.1:2(anonymous)@comments.js?ver=1.0.0:[email protected]?ver=3.7.1:[email protected]?ver=3.7.1:2
comments.js?ver=1.0.0:48 Error uploading image:
- {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
- abort: ƒ (e)
- always: ƒ ()
- catch: ƒ (e)
- complete: ƒ ()
- done: ƒ ()
- error: ƒ ()
- fail: ƒ ()
- getAllResponseHeaders: ƒ ()
- getResponseHeader: ƒ (e)
- overrideMimeType: ƒ (e)
- pipe: ƒ ()
- progress: ƒ ()
- promise: ƒ (e)
- readyState: 4
- responseJSON: {code: ‘rest_cookie_invalid_nonce’, message: ‘Cookie check failed’, data: {…}}
- responseText: “{\”code\”:\”rest_cookie_invalid_nonce\”,\”message\”:\”Cookie check failed\”,\”data\”:{\”status\”:403}}”
- setRequestHeader: ƒ (e,t)
- state: ƒ ()
- status: 403
- statusCode: ƒ (e)
- statusText: “Forbidden”
- success: ƒ ()
- then: ƒ (t,n,r)
- Prototype: Object
(anonymous)@comments.js?ver=1.0.0:48await in (anonymous)[email protected]?ver=3.7.1:[email protected]?ver=3.7.1:2
I solved the uploading comment with images specifying two different noces. One for the image and other for the comment. It works!
wp_localize_script('groupsEgt-script', 'mediaUploadSettings', [
'root' => esc_url(rest_url()), // URL de la API REST
'nonce' => wp_create_nonce('wp_rest'), // Nonce correcto para la API REST
]);
wp_localize_script('groupsEgt-script', 'commentsEgt', [
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('commentsEgt_nonce'), // Nonce para AJAX
]);jQuery(document).ready(function ($) {
const commentForm = $("#groups-egt-comment-form");
commentForm.on("submit", async function (event) {
event.preventDefault();
const commentContent = $("#groups-egt-comment").val().trim();
const groupId = $("#groups_egt_form_group_id").val();
const userId = $("#groups_egt_form_user_id").val();
console.log("User ID:", userId);
const restNonce = mediaUploadSettings.nonce; // Nonce correcto para API REST
const ajaxNonce = commentsEgt.nonce; // Nonce para comentarios
if (!commentContent || !groupId || !userId) {
alert("All fields are required.");
return;
}
let imageUrl = null; // URL de la imagen subida
// Subir imagen si existe
const imageInput = $("#comment_image")[0];
if (imageInput && imageInput.files.length > 0) {
const imageFile = imageInput.files[0];
let formData = new FormData();
formData.append("file", imageFile);
formData.append("title", imageFile.name);
formData.append("alt_text", "Comment image");
formData.append("caption", "Uploaded via GroupsEGT");
formData.append("description", "Image for comment");
try {
let uploadResponse = await $.ajax({
url: mediaUploadSettings.root + "wp/v2/media",
method: "POST",
headers: {
"X-WP-Nonce": restNonce,
},
contentType: false,
processData: false,
data: formData,
});
imageUrl = uploadResponse.source_url;
} catch (error) {
console.error("Error uploading image:", error);
alert("Error uploading the image, try again.");
return;
}
}
// Enviar el comentario con la imagen adjunta
$.ajax({
url: commentsEgt.ajaxurl,
method: "POST",
data: {
action: "create_comment",
comment: commentContent,
group_id: groupId,
user_id: userId,
media: imageUrl,
nonce: ajaxNonce,
},
success: function (response) {
console.log("AJAX Response frontend:", response);
if (response.success) {
alert("Comment added successfully!");
commentForm[0].reset();
loadComments(groupId);
} else {
console.error("Error adding comment:", response.data.message);
alert("Error adding comment. Please try again.");
}
},
error: function (error) {
console.error("Error adding comment:", error);
alert("Error adding comment. Please try again.");
}
});
});
}); - {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
The topic ‘Invalid nonce at loading commets’ is closed to new replies.
(@franclobo)
1 year, 3 months ago
Hello, I’m developing a plugin. It has subjects posted as post_type=’group’, then each group has comments post_type=’group-comment’ I didn’t used ‘comment’ because it is a special word of WordPress, and each ‘comment’ has responses post_type=’response’. In the groups’ menu in wp-admin I want to load the al comments, but I have the error ‘Invalid nonce’. I have been checkiing the error with chatGPT but it walks in circles. I’m using two directories one for admin and another for public UI where usera are able to create comments on the groups.
When I load the groups I have the data successfully, but when I load the comments I have the following error:
admin-groups.js loaded
admin-groups.js?ver=1.0.0:2
admin-comments.js?ver=1.0.0:2 Admin comments JS loaded
admin-comments.js?ver=1.0.0:3 Nonce in admin-comments.js: acb25db75b
admin-groups.js?ver=1.0.0:53
admin-comments.js?ver=1.0.0:48
admin-comments.js?ver=1.0.0:8 Loading comments…
admin-comments.js?ver=1.0.0:10 Nonce enviado: acb25db75b
admin-comments.js?ver=1.0.0:21 AJAX Response comments loaded:
admin-comments.js?ver=1.0.0:38 AJAX Error: Invalid [email protected]?ver=1.0.0:[email protected]?c=1…olyfill&ver=6.7.1:[email protected]?c=1…olyfill&ver=6.7.1:[email protected]?c=1…olyfill&ver=6.7.1:2(anonymous)@load-scripts.php?c=1…olyfill&ver=6.7.1:[email protected]?c=1…olyfill&ver=6.7.1:[email protected]?c=1…olyfill&ver=6.7.1:2(anonymous)@load-scripts.php?c=1…olyfill&ver=6.7.1:5(anonymous)@load-scripts.php?c=1…olyfill&ver=6.7.1:5(anonymous)@admin-comments.js?ver=1.0.0:[email protected]?c=1…olyfill&ver=6.7.1:2