• Resolved franclobo

    (@franclobo)


    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

    1. {ajaxurl: ‘https://localhost/southamericantravelers.club/wp-admin/admin-ajax.php’, nonce: ‘acb25db75b’}

    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

    1. {action: ‘load_groups’, nonce: ‘acb25db75b’}

    admin-comments.js?ver=1.0.0:48

    1. {action: ‘load_comments’, nonce: ‘acb25db75b’}

    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:

    1. {success: false, data: {…}}

    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

    function groupsEgt_admin_enqueue_scripts() {

        wp_enqueue_media();

        // Generar un solo nonce

        $comments_nonce = wp_create_nonce('commentsEgt_nonce');

        error_log("Nonce generado en enqueue: " . $comments_nonce);

        wp_enqueue_script(

            'groupsEgt-admin-groups',

            plugin_dir_url(__FILE__) . 'admin/js/admin-groups.js',

            ['jquery', 'wp-api-fetch'],

            '1.0.0',

            true

        );

        wp_enqueue_script(

            'groupsEgt-admin-comments',

            plugin_dir_url(__FILE__) . 'admin/js/admin-comments.js',

            ['jquery', 'wp-api-fetch'],

            '1.0.0',

            true

        );

        wp_localize_script('groupsEgt-admin-comments', 'commentsEgt', [

            'ajaxurl' => admin_url('admin-ajax.php'),

            'nonce' => $comments_nonce // Usar el mismo nonce

        ]);

        wp_localize_script('groupsEgt-admin-groups', 'commentsEgt', [

            'ajaxurl' => admin_url('admin-ajax.php'),

            'nonce' => $comments_nonce // Usar el mismo nonce

        ]);

        wp_enqueue_style(

            'groupsEgt-admin-style',

            plugin_dir_url(__FILE__) . 'admin/css/style.css'

        );

    }

    add_action('admin_enqueue_scripts', 'groupsEgt_admin_enqueue_scripts');
    console.log('Admin comments JS loaded');
    console.log("Nonce in admin-comments.js:", commentsEgt.nonce);
    jQuery(document).ready(function($) {

    // Cargar comentarios al hacer clic en "Load Comments"
    $('#comments-load-comments').on('click', function() {
    console.log('Loading comments...');
    const groupId = $('#comment-group').val(); // Obtener el ID del grupo seleccionado
    console.log('Nonce enviado: ', commentsEgt.nonce);

    $.ajax({
    url: commentsEgt.ajaxurl,
    method: 'POST',
    data: {
    action: 'load_comments',
    nonce: commentsEgt.nonce,
    group_id: groupId,
    },
    success: function(response) {
    console.log("AJAX Response comments loaded:", response);
    if (response.success) {
    const comments = response.data.comments;
    let commentsHtml = '';
    comments.forEach(function(comment) {
    commentsHtml +=
    <tr><br> <td>${comment.id}</td><br> <td>${comment.comment}</td><br> <td>${comment.group}</td><br> <td><a href="${comment.link}" target="_blank">View</a></td><br> <td><button class="edit-comment" data-id="${comment.id}">Edit</button></td><br> <td><button class="delete-comment" data-id="${comment.id}">Delete</button></td><br> </tr>;
    });
    $('#comments-table-body').html(commentsHtml);
    } else {
    alert('Error loading comments');
    console.error("AJAX Error:", response.data.message);
    }
    },
    error: function(xhr, status, error) {
    console.error("AJAX Error:", error);
    alert("Error loading comments");
    }
    });
    });

    console.log({
    action: 'load_comments',
    nonce: commentsEgt.nonce
    })
    <?php

    require_once plugin_dir_path(__FILE__) . 'class-groups-egt-comment.php';

    class GroupsEGT_Comment_Ajax {

        public function __construct() {

            add_action('wp_ajax_load_comments', [$this, 'load_comments']);

            add_action('wp_ajax_load_comment_data', [$this, 'load_comment_data']);

            add_action('wp_ajax_create_comment', [$this, 'create_comment']);

            add_action('wp_ajax_update_comment', [$this, 'update_comment']);

            add_action('wp_ajax_delete_comment', [$this, 'delete_comment']);

        }

        // Cargar comentarios

        public function load_comments() {

            error_log("POST recibido: " . print_r($_POST, true));

            if ( !isset($_POST['nonce']) ) {

                error_log("No se recibió el nonce.");

                wp_send_json_error(['message' => 'Nonce not sent']);

            }

            $nonce_valid = wp_verify_nonce($_POST['nonce'], 'commentsEgt_nonce');

            error_log("Resultado de wp_verify_nonce: " . var_export($nonce_valid, true));

            if ( !$nonce_valid ) {

                error_log("Nonce inválido: " . $_POST['nonce']);

                wp_send_json_error(['message' => 'Invalid nonce']);

            }

            // Eliminar o comentar la siguiente línea:

            // wp_send_json_error(['message' => 'Ocurrió un error al cargar los comentarios']);

            $group_id = intval($_POST['group_id']);  // Aseguramos que es el ID del grupo

            $comments = [];

            // Recuperar comentarios asociados al grupo

            $comment_posts = get_posts([

                'post_type' => 'group_comment',

                'posts_per_page' => -1,

                'post_parent' => $group_id,

            ]);

            foreach ($comment_posts as $post) {

                // Obtener el nombre del grupo relacionado, si es necesario

                $group_title = get_the_title($group_id); // Ya tienes el ID del grupo

                $comments[] = [

                    'id' => $post->ID,

                    'comment' => $post->post_content,

                    'group' => $group_title, // Nombre del grupo

                    'image_id' => get_post_thumbnail_id($post->ID), // Si hay imagen asociada

                    'link' => get_permalink($post->ID), // Enlace al comentario, si es necesario

                ];

            }

            wp_send_json_success(['comments' => $comments]);

        }

        // Cargar datos de un comentario

        public function load_comment_data() {

            // Verificar nonce de seguridad

            if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'commentsEgt_nonce')) {

                wp_send_json_error(['message' => 'Invalid nonce']);

                return;

            }

            $comment_id = intval($_POST['comment_id']);

            $comment_post = get_post($comment_id);

            if (!$comment_post) {

                wp_send_json_error(['message' => 'Comment not found']);

                return;

            }

            $comment = [

                'id' => $comment_post->ID,

                'comment' => $comment_post->post_content,

                'image_id' => get_post_thumbnail_id($comment_post->ID),

            ];

            wp_send_json_success(['comment' => $comment]);

        }

        // Crear comentario

        public function create_comment() {

            // Verificar nonce de seguridad

            if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'commentsEgt_nonce')) {

                wp_send_json_error(['message' => 'Invalid nonce']);

                return;

            }

            $comment = sanitize_textarea_field($_POST['comment']);

            $group_id = intval($_POST['group_id']);  // Aseguramos que es el ID del grupo

            $user_id = get_current_user_id();

            $image_id = isset($_POST['image_id']) ? intval($_POST['image_id']) : null;

            error_log("Datos recibidos: Comment: $comment, Group ID: $group_id, User ID: $user_id, Image ID: $image_id");

            // Crear el comentario

            $comment_obj = new GroupsEGT_Comment($comment, $group_id, $user_id, $image_id);

            $comment_id = $comment_obj->create_comment();

            if ($comment_id) {

                wp_send_json_success(['comment_id' => $comment_id]);

            } else {

                wp_send_json_error(['message' => 'Failed to create comment']);

            }

        }

        // Actualizar comentario

        public function update_comment() {

            // Verificar nonce de seguridad

            if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'commentsEgt_nonce')) {

                wp_send_json_error(['message' => 'Invalid nonce']);

                return;

            }

            $comment_id = intval($_POST['comment_id']);

            $comment = sanitize_textarea_field($_POST['comment']);

            $image_id = isset($_POST['image_id']) ? intval($_POST['image_id']) : null;

            // Actualizar comentario

            $comment_obj = new GroupsEGT_Comment($comment, 0, 0, $image_id);

            $updated = $comment_obj->update_comment($comment_id);

            if ($updated) {

                wp_send_json_success(['comment_id' => $comment_id]);

            } else {

                wp_send_json_error(['message' => 'Failed to update comment']);

            }

        }

        // Eliminar comentario

        public function delete_comment() {

            // Verificar nonce de seguridad

            if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'commentsEgt_nonce')) {

                wp_send_json_error(['message' => 'Invalid nonce']);

                return;

            }

            $comment_id = intval($_POST['comment_id']);

            // Eliminar comentario

            $comment_obj = new GroupsEGT_Comment('', 0, 0);

            $deleted = $comment_obj->delete_comment($comment_id);

            if ($deleted) {

                wp_send_json_success(['comment_id' => $comment_id]);

            } else {

                wp_send_json_error(['message' => 'Failed to delete comment']);

            }

        }

    }
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    The default encoding used by .ajax() doesn’t always play well with PHP. Try including dataType : '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.

    Thread Starter franclobo

    (@franclobo)

    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.

    Thread Starter franclobo

    (@franclobo)

    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:

    1. {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
      1. abort: ƒ (e)
      2. always: ƒ ()
      3. catch: ƒ (e)
      4. complete: ƒ ()
      5. done: ƒ ()
      6. error: ƒ ()
      7. fail: ƒ ()
      8. getAllResponseHeaders: ƒ ()
      9. getResponseHeader: ƒ (e)
      10. overrideMimeType: ƒ (e)
      11. pipe: ƒ ()
      12. progress: ƒ ()
      13. promise: ƒ (e)
      14. readyState: 4
      15. responseJSON: {code: ‘rest_cookie_invalid_nonce’, message: ‘Cookie check failed’, data: {…}}
      16. responseText: “{\”code\”:\”rest_cookie_invalid_nonce\”,\”message\”:\”Cookie check failed\”,\”data\”:{\”status\”:403}}”
      17. setRequestHeader: ƒ (e,t)
      18. state: ƒ ()
      19. status: 403
      20. statusCode: ƒ (e)
      21. statusText: “Forbidden”
      22. success: ƒ ()
      23. then: ƒ (t,n,r)
      24. 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:

    1. {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
      1. abort: ƒ (e)
      2. always: ƒ ()
      3. catch: ƒ (e)
      4. complete: ƒ ()
      5. done: ƒ ()
      6. error: ƒ ()
      7. fail: ƒ ()
      8. getAllResponseHeaders: ƒ ()
      9. getResponseHeader: ƒ (e)
      10. overrideMimeType: ƒ (e)
      11. pipe: ƒ ()
      12. progress: ƒ ()
      13. promise: ƒ (e)
      14. readyState: 4
      15. responseJSON: {code: ‘rest_cookie_invalid_nonce’, message: ‘Cookie check failed’, data: {…}}
      16. responseText: “{\”code\”:\”rest_cookie_invalid_nonce\”,\”message\”:\”Cookie check failed\”,\”data\”:{\”status\”:403}}”
      17. setRequestHeader: ƒ (e,t)
      18. state: ƒ ()
      19. status: 403
      20. statusCode: ƒ (e)
      21. statusText: “Forbidden”
      22. success: ƒ ()
      23. then: ƒ (t,n,r)
      24. 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

    Thread Starter franclobo

    (@franclobo)

    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.");
    }
    });
    });
    });
Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Invalid nonce at loading commets’ is closed to new replies.