首页 > 解决方案 > Yet another WordPress Ajax 400 Bad Request problem

问题描述

I am certain I am making a basic mistake here. I am getting the lovely 400 Bad Request response from WordPress when I try to make an Ajax call. I have one Ajax call that works, and this one that does not. I have looked at several posts both here and elsewhere, but remain stumped as to where I have erred.

Okay, the relevant code. First, here is how I do the add_action and script registration:

if ($_GET["page"] == "krudkat_data_structures") {
    add_action("wp_ajax_krud_save_new_connection", "krud_save_new_connection");
}

// Other Stuff, for the Ajax call that works.

if ($_GET["page"] == "krudkat_data_structures") {
    wp_register_script("krud_data_structures", plugin_dir_url( __DIR__ ) . "/js/dataStructures.js", array("jquery"));
    wp_localize_script("krud_data_structures", "krudAjax", array( "ajaxurl" => admin_url("admin-ajax.php")));
    wp_enqueue_script("krud_data_structures");
}

This sits in a function outside of a class. My JS call is like this:

var krudNewConnect = { action:"krud_save_new_connection",
    dbname:$("#krud_new_dbname").val().trim(),
    dbhost:$("#krud_new_dbhost").val().trim(),
    dbconnect:$("#krud_new_dbconnect").val().trim(),
    dbusername:$("#krud_new_dbusername").val().trim(),
    dbpassword:$("#krud_new_dbpassword").val() };
$.post(krudAjax.ajaxurl, krudNewConnect, function(newConnectData) {
    console.log(newConnectData);
});

Finally, my PHP method is, thus far, very simple:

function krud_save_new_connection() {
    $dbname = $_POST["dbname"];
    $dbhost = $_POST["dbhost"];
    $dbconnect = $_POST["dbconnect"];
    $dbusername = $_POST["dbusername"];
    $dbpassword = $_POST["dbpassword"];
    $dbport = 0;
    $dbsocket = '';
    if (!empty($dbconnect)) {
        if (is_numeric($dbconnect)) {
            $dbport = $dbconnect * 1;
        } else {
            $dbsocket = $dbconnect;
        }
    }
    echo "Port: " . $dbport . "\nSocket: " . $dbsocket;
    wp_die();
}

This is not expected to work when somebody is not logged in as an admin, so I omitted the no_priv add_action. I am certain this is not the problem; I did add that into my code and it had no impact.

What newbie mistake have I made? :)

标签: wordpress

解决方案


首先,将脚本排入队列,然后为 ajax 本地化脚本。它将解决问题。检查法典:https ://codex.wordpress.org/AJAX_in_Plugins


推荐阅读