Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress admin ajax.php 400 bad request

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.sstatic.net/5SiDd.png

https://i.sstatic.net/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(); 
    }
?>
like image 375
Anthony Medina Avatar asked Jan 24 '26 20:01

Anthony Medina


2 Answers

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.

like image 50
RWC Avatar answered Jan 26 '26 08:01

RWC


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/

like image 29
RSPR Avatar answered Jan 26 '26 08:01

RSPR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!