• My plugin contains a function that is called to create a plugin page. It requests 3 input parameters from the user through standard JS modal windows, however, a problem occurs when transferring parameters to the server. I am sending AJAX parameters by request and creating an AJAX request holder on the server side. I’m already confused about what the error might be. Tortured both friends and ChatGPT to death. Help someone who understands

    //Выводим страницу с урезанной кнопкой установки

    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('Unauthorizated');

            //Запоминаем результат функции

            $_SESSION['python_install_result'] = "Ошибка при запуске установки Python: Вы не авторизованы!";

          }

        } else {

          //Возвращаем ошибку

          wp_send_json_error('Not AJAX request');

          //Запоминаем результат функции

          $_SESSION['python_install_result'] = "Ошибка при запуске установки Python: AJAX запрос не распознан";

        }

        exit;

      });

      //Диалог с пользователем

      ?><script>

        //Холдеры ответов пользователя

        let dockerPassword = null;

        let dockerAccessMethod = null;

        //Функция отправки параметров

        function sendFormData(accessMethod, dockerPassword) {

          //Создаем объект XMLHttpRequest

          const xhr = new XMLHttpRequest();

          //Устанавливаем URL сервера

          xhr.open("POST", "<?php echo admin_url('admin-ajax.php') ?>", 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});

            } else {

              //Отправляем ошибку

              console.error([${xhr.status}] Error: ${xhr.statusText});

            }

          };

          //Обработчик события для ошибки

          xhr.onerror = function() {

            //Отправляем ошибку

            console.error("[Error] Failed to send data");

          };

        }

        //При отображении всех компонентов страницы

        document.addEventListener('DOMContentLoaded', function() {

          //Запрашиваем разрешение на использование Docker

          new Promise((resolve, reject) => {

            setTimeout(() => {

              //Запрашиваем доступ к Docker

              const useDocker = confirm('Использовать Docker?');

              resolve(useDocker);

            }, 0);

          })

          .then((useDocker) => {

            if (useDocker) {

              //Запрашиваем пароль от Docker

              return new Promise((resolve, reject) => {

                setTimeout(() => {

                  //Запрашиваем пароль от Docker

                  dockerPassword = prompt('Введите пароль от Docker, если требуется', '');

                  //Если пароль получен

                  if (dockerPassword !== null) {

                    resolve(dockerPassword);

                  } else {

                    reject(null);

                  }

                }, 0);

              });

            } else {

              //Пользователь отказался от использования Docker

              return Promise.reject('Docker isn\'t in use');

            }

          })

          .then((password) => {

            //Запрашиваем метод доступа к Docker

            return new Promise((resolve, reject) => {

              setTimeout(() => {

                //Запрашиваем метод доступа к Docker

                dockerAccessMethod = prompt('Введите способ доступа к Docker. (Например: ssh localhost -p222)', '');

                //Если метод доступа получен

                if (dockerAccessMethod !== null) {

                  resolve(dockerAccessMethod);

                } else {

                  reject(null);

                }

              }, 0);

            });

          })

          .then((accessMethod) => {

            //Отправляем параметры

            sendFormData(accessMethod, dockerPassword);

          })

          .catch((error) => {

            //Отправляем параметры

            sendFormData(null, null);

          });

        });

      </script><?php

    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi @srrok! Could you provide a little more information which may help debug the issue? Where exactly is your code failing? Is the issue in accessing values like $_POST['docker_access_method'] in your wp_ajax_python_install action, or somewhere else?

    More details could help figure out the exact problem. I see a few potential concerns but could use the extra info first. Thank you!

      Moderator bcworkz

      (@bcworkz)

      Like Zack said, more information would be useful. How and when are you calling ai_parser_non_sudo_install_python_page()? We will get 400 errors when the requested action hook had not been added for an admin-ajax.php request. If your ai_parser_non_sudo_install_python_page() function is not called in that context, it would explain the 400 error.

      Usually the add_action() call for Ajax callbacks reside outside of any theme or plugin functions, ensuring the hook is added for admin-ajax.php requests.

    Viewing 2 replies - 1 through 2 (of 2 total)

    The topic ‘When using AJAX, an error occurs with the HTTP code 400’ is closed to new replies.