HTTP code 400 error when using AJAX
My plugin contains a function that is called to create the plugin page. It is requesting 3 input parameters from the user via a standard JS modal window, but is having problems transferring the parameters to the server. I am sending the AJAX parameters via a request and creating the AJAX request holder on the server side. I've lost track of what the error might be. Please help if you know what you are doing.
//Выводим страницу с урезанной кнопкой установки
function ai_parser_non_sudo_install_python_page() {
//Обработка POST запроса через AJAX
add_action('wp_ajax_python_install', function () {
//Если AJAX запрос получен верно
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_ WITH']) === 'xmlhttprequest') {
//Если пользователь вторизован
if (is_user_logged_in()) {
// Получаем параметры формы
$docker_access_method = isset($_POST['docker_access_method']) ? $_POST['docker_access_method'] : ";
$docker_password = isset($_POST['docker_password']) ? $_POST['docker_password'] : ";
try {
//Выполняем установку Docker с помощью функции ai_parser_non_sudo_install_python()
$result = ai_parser_non_sudo_install_python($docker_password, $docker_access_method);
// Отправляем ответ AJAX с сообщением об успешной обработке запроса и результатом установки
wp_send_json_success(array(
'message' => 'Docker installation request processed successfully',
'python' => $result
));
//Запоминаем результат функции в сессии
$_SESSION['python_install_result'] = $result;
} catch (Exception $e) {
//Записываем сообщение об ошибке в журнал
error_log("Error during Docker installation: " . $e->getMessage());
//Отправляем ответ AJAX с сообщением об ошибке
wp_send_json_error('Failed to install Docker. Please check the logs for more details.');
//Запоминаем сообщение об ошибке в сессии
$_SESSION['python_install_result'] = 'Failed to install Docker: ' . $e->getMessage();
}
} else {
//Возвращаем ошибку
wp_send_json_error('Unauthorized');
//Запоминаем результат функции
$_SESSION['python_install_result'] = "Ошибка при запуске установки Python: Вы не авторизованы! ";
}
} else {
//Возвращаем ошибку
wp_send_json_error('Not AJAX request');
//Запоминаем результат функции
$_SESSION['python_install_result'] = "Ошибка при запуске установки Python: AJAX запрос не распознан ";
}
exit;
});
//Диалог с пользователем
? >
//Холдеры ответов пользователя
let dockerPassword = null;
let dockerAccessMethod = null;
//Функция отправки параметров
function sendFormData(accessMethod, dockerPassword) {
//Создаем объект XMLHttpRequest
const xhr = new XMLHttpRequest();
//Устанавливаем URL сервера
xhr.open("POST", "", true);
//Устанавливаем заголовок для типа контента
xhr.setRequestHeader("Content-Type", "application/json");
//Отправляем запрос
xhr.send(JSON.stringify({
'action': 'python_install',
'accessMethod': accessMethod,
'dockerPassword': dockerPassword
}));
//Обработчик события для успешного ответа
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
//Обработка ответа сервера
const response = JSON.parse(xhr.response);
console.log([${xhr.status}] Server response: ${response} (English):
} else {
// Return Error
console.error( [${xhr.status}] Error: ${xhr.statusText});
}
};
//Return results
xhr.onerror = function() {
//Return results
console.error("[Error] Failed to send data");
};
}
// Realization of multiple components
document.addEventListener('DOMContentLoaded', function() { // set the Docker component new Promise((resolve, rejection) => { setTimeout(() => { // Set the component type of the Docker component to JavaScript new Promise((resolve, rejection) => { setTimeout(() => { // Set the component type of the Docker component to JavaScript new Promise((resolve, rejection) => { setTimeout(() => { // Set the Docker component's component type to JavaScript new Promise((resolve, rejection) => { setTimeout(() => { // Set the Docker component's component type to JavaScript new Promise((resolve, rejection) => { setTimeout(() => { // Set the Docker component's component type to JavaScript new Promise((resolve
, rejection) => { setTimeout(() => { Docker const useDocker = confirmed('Do you want to use Docker?'); resolve(useDocker); }, 0); }) . then((useDocker) => { if (useDocker) { // get the information from Docker return new Promise((resolve, rejection) => { setTimeout(() => { // resolve the password from Docker dockerPassword = prompt('Resolve the password from Docker or it will fail', "); // Resolve the password from Docker if (dockerPassword ! == null) { resolve(dockerPassword); } else { rejection(null); } }, 0); }); } else { //Feedback from Docker return Promise.reject('Docker isn 't in use '); } }) .then((password) => { // Methods that use the Docker service return new Promise((resolve, rejection) => { setTimeout(() => { // Methods that use the Docker service method dockerAccessMethod = prompt('Log in to the Docker service. (Name: ssh localhost - p222)', "); // Define a valid method if (dockerAccessMethod ! == null) { resolve(dockerAccessMethod); } else { rejection(null); } }, 0); }); }) .then((accessMethod) => { //Execute sendFormData(accessMethod, dockerPassword); }) .catch((error) => { //execute sendFormData(null, null); }); }); <?php copy code