Wordpress admin ajax.php 400 bad request

13,574

Solution 1

If you end up here because you received a 400 error (Bad Request), the reason could be making the AJAX request, when the user is not logged in.

You have to change your code from

wp_ajax_my_action', 'my_action' ); 

to

wp_ajax_nopriv_my_action', 'my_action' ); 

Maybe it helps somebody else.

Solution 2

The code registers your Ajax handler, but when you only run it on wp_enqueue_scripts, it's already too late and wp_ajax_nopriv_ hooks are already run.

Know more about Wordpress Ajax:

https://codex.wordpress.org/AJAX_in_Plugins https://developer.wordpress.org/plugins/javascript/ajax/

Share:
13,574

Related videos on Youtube

Anthony Medina
Author by

Anthony Medina

Estudiante del ultimo año de ingeniería en Informática, administrador de Friki Bloggeo y amante de los idiomas. Defensor a morir de PHP, sobre cualquier otras tecnologías, un poco conservador en este aspecto.

Updated on June 04, 2022

Comments

  • Anthony Medina
    Anthony Medina almost 2 years

    It turns out that I'm making a Wordpress plugin in which I need to make an AJAX to the file "admin_ajax.php" of Wordpress, but when sending the request, the client gives me error 400 (Bad Request) and I do not understand for what reason.

    captures

    https://i.stack.imgur.com/5SiDd.png

    https://i.stack.imgur.com/tPD6o.png

    Javascript:

    $.post(window.dibibot.ajax_uri, {
        action: "dibibot_check_message_read",
        to: (window.dibibot.USER_KEYS.split(":")[1]).toString(),
        message_id: JSON.stringify(data.message)
    }, function(response) {
        console.log(response);
    });
    

    Ajax php function:

    <?php
        function dibibot_check_message_read() {
            global $wpdb;
            $conversation_guid = $_POST['to'];
            $message_id = json_decode($_POST['message_id'], true);
    
            $conversation = $wpdb->get_var("SELECT metadata FROM " . $wpdb->prefix . "dibibot_conversations WHERE guid = '".$conversation_guid."'");
            $conversation = maybe_unserialize($conversation);
            for ($j=0; $j < count($message_id) ; $j++) { 
                for ($i=0; $i < count($conversation); $i++) {
                    if($conversation[$i]['id'] == $message_id[$j]) {
                        $conversation[$i]['status'] = 2;
                        break;
                    }
                }
            }
            $result = $wpdb->update($wpdb->prefix . 'dibibot_conversations', [ "metadata" => maybe_serialize($conversation) ], [ "guid" => $conversation_guid]);
            echo $result ? 1 : 0;
            wp_die(); 
        }
    ?>
    
  • bhv
    bhv over 2 years
    another case - ajax action hooks have to write where admin code runs. if hooks added where is_admin is false then it wont works