Запрос Ajax на сайте в каталоге wp-admin на сервере WordPress возвращает 400 Bad request

Ну, заранее спасибо, что нашли время, чтобы прочитать мой вопрос.
Ситуация следующая:

У меня есть сервер Wrodpress с единственным сайтом в wp-admin/sites/contactform/index.php.
С этого сайта я хочу сделать вызов Ajax, но получаю сообщение «/wp-admin/admin-ajax.php:1 Failed». для загрузки ресурса: сервер ответил со статусом 400 (Bad Request) ' ошибка при начальной загрузке сайта и ошибка
' https://THECORRECTURL/wp-admin/admin-ajax.php 400 (Bad Request)' когда я выполняю метод.
Подозреваю, что ошибки спровоцированы отсутствием прав доступа к файлу admin-ajax.php.
Я хотел бы знать, что вы думаете.

Вот код:

В файле js в каталоге «contactform/dt/wb.js»:

      jQuery(document).ready(function($) {
    $('#btn-x').click(function() {
        $.ajax({
            url: '../../admin-ajax.php',  // The URL of the WordPress AJAX handler
            type: 'POST',  // The HTTP method of the request
            data: {  // The data to be sent with the request
                action: 'usystorequest',
                
            },
            success: function(response) {  // A function to be called if the request is successful
                if (response) {$('#mail_sent').show(); //mail got sent
                
                }
                else { $('#mail_not_sent').show(); //mail didnt get sent

                }
            }
        });
    }); 
});

В файле functions.php в контактной форме:

      add_action('wp_enqueue_scripts', function(){

    wp_enqueue_script('wb',  get_stylesheet_directory_uri() . '/dt/wb.js',['jquery'], '1.0', false);
    wp_enqueue_script('jquery',  get_stylesheet_directory_uri() . '/dt/jquery-3.4.1.min.js',[], '1.0', false);
});
//Function executed by ajax call
add_action("wp_ajax_usystorequest", "usystorequest");
add_action("wp_ajax_nopriv_usystorequest", "usystorequest");
function usystorequest(){
 echo ':test:';
 wp_die();
}

(Я не использую плагин Contactform, потому что я отправляю информацию, которая рассчитывается в js, а сайт отделен от обычной структуры с темами и плагинами из-за конфликтов с плагинами и темами - так просто проще. Предыдущая версия то, что я сейчас хочу обновить, там уже работает, только без ajax)

Я добавил вызов nopriv ajax, поэтому вам не нужны права администратора (войти в систему) для выполнения функции ajax.

Функция usystorequest максимально упрощена, чтобы исключить источник ошибки в коде.
Я попытался сделать это с помощью специального обработчика ajax, вот код. У меня такая же ошибка:

      FUNCTIONS.PHP
// Step 1: Add a new endpoint in your functions.php file
add_action( 'init', 'add_my_endpoint' );
function add_my_endpoint() {
  add_rewrite_endpoint( 'my-endpoint', EP_ROOT );
}

// Step 2: Add a function to handle the request
add_action( 'template_redirect', 'my_endpoint_handler' );
function my_endpoint_handler() {
  global $wp_query;
  if ( ! isset( $wp_query->query_vars['my-endpoint'] ) ) {
    return;
  }
  // Handle the request
  if ( $_SERVER['REQUEST_METHOD'] == 'GET' && isset( $_GET['action'] ) && $_GET['action'] == 'usystorequest' ) {
    usystorequest();
    exit;
  }
}

JAVASCRIPT WB.JS FILE
// Step 3: Update your AJAX call to use the new endpoint
jQuery(document).ready(function($) {
  $('#btn-x').click(function() {
    $.ajax({
      url: '/?my-endpoint=1',  // The URL of the custom AJAX handler
      type: 'GET',  // The HTTP method of the request
      data: {  // The data to be sent with the request
        action: 'usystorequest',  // The name of the action to be triggered in the WordPress backend (functions.php)
      },
      success: function(response) {  // A function to be called if the request is successful
        if (response) {$('#mail_sent').show(); //mail got sent

        }
        else { $('#mail_not_sent').show(); //mail didnt get sent

        }
      }
    });
  });
});

0 ответов

Другие вопросы по тегам