使用基于类的文件的错误请求400

时间:2021-02-09 作者:mybecks

after digging through a lot of Ajax Bad Request 400 problems here on SO, that, unfortunately, didn\'t help me to solve this problem.

After instantiating my custom post, I add a submenu page where I instantiate my admin functionality, which in turn execute some ajax.

custom post:

class customDomain{

private $wpPluginAdmin;

public function __construct(){
  ...
  add_action(\'admin_menu\', array($this, \'add_sub_menu_pages\'));
  ...
}

public function add_sub_menu_pages()
{
  add_submenu_page(
    ...
  );
  $this->wpPluginAdmin = new PluginAdmin();
}

}//endclass
$custom_domain = new CustomDomain();

PluginAdmin:

  
 //...
public function __construct()
{
  $this->pluginPath = dirname(__FILE__);
  $this->db_handler = DatabaseHandler::get_instance();

  add_action(\'admin_print_styles\', array($this, \'add_admin_styles\'));
  add_action(\'admin_enqueue_scripts\', array($this, \'add_admin_scripts\'));
  add_action(\'wp_ajax_add_vehicle\', array($this, \'add_vehicle\'));
  add_action(\'wp_ajax_nopriv_add_vehicle\', array($this, \'add_vehicle\'));
}

public function add_admin_scripts()
{
  wp_enqueue_script(\'admin_scripts\', plugins_url(\'js/functions.admin.js\', __FILE__), array(\'jquery\'));
  wp_localize_script(
    \'admin_scripts\',
    \'ajax_object\',
    array(
      \'ajaxurl\' => admin_url(\'admin-ajax.php\'),
      \'nonce\' => wp_create_nonce(\'ajax-nonce\')
    )
  );
}

public function add_vehicle()
{
  // var_dump($_POST);
  // die();

  $nonce = $_POST[\'nonce\'];

  if (!wp_verify_nonce($nonce, \'ajax-nonce\')) {
    die(\'Busted!\');
  }

  //add new vehicle to database
  $this->db_handler->admin_insert_vehicle($_POST[\'vehicle\']);
  $id = $this->db_handler->get_last_insert_id();
  $vehicle = (object) array(
    \'id\' => $id,
    \'description\' => $_POST[\'vehicle\']
  );

  $response = json_encode($vehicle);

  // response output -> sent back to javascript file
  // header("Content-Type: application/json");
  wp_send_json($response);
}

My JS function:

var $ = jQuery;
var addVehicle = function () {

    $(\'.add-vehicle\').click(function () {
        var data = {
            action: \'add_vehicle\',
            nonce: ajax_object.nonce,
            vehicle: {
                \'description\': $(\'#vehicle_description\').val(),
                \'radio_id\': $(\'#vehicle_radio_id\').val(),
                \'location\': $(\'#vehicle_location\').val(),
            }
        };

        $.ajax({
            type: \'POST\',
            url: ajaxurl,
            data: data,
            success: function (data, textStatus, XMLHttpRequest) {
                $(\'#message\').show();

                $(\'.tab-vehicle\').append(\'<tr>\' +
                    \'<td>\' + data.id + \'</td>\' +
                    \'<td>\' + data.description + \'</td>\' +
                    \'<td>\' + data.radio_id + \'</td>\' +
                    \'<td>\' + data.location + \'</td>\' +
                    \'<td><i class="fas fa-edit"></i></td>\' +
                    \'<td><i class="fas fa-trash-alt"></i></td>\' +
                    \'</tr>\');
                $(\'#message\').fadeOut(2000);
            },
            error: function (MLHttpRequest, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        });
    });
};
jQuery(document).ready(function ($) {
    addVehicle();
});

When I\'m debugging into the JS function and go step by step, I manage to get into the error callback, when just executing it, it looks like nothing happens. The add_vehicle function isn\'t called.

Sending out a postman request to http://localhost:8000/wp-admin/admin-ajax.php?action=add_vehicle return 0 with an HTTP 400. At least I expected the same result when my JS coding is executed, but neither in the console nor anywhere else is the HTTP 400 is displayed.

thanks, mybecks

EDIT:

I have refactored the class AdminPlugin that it got instantiated after the plugin gets activated (so I removed it from the custom post add menu action), now I got a positive response (also with postman). But nothing of my "debugging" try is working and it looks like nothing of the code is executed.

PluginAdmin:

class PluginAdmin {  
 //...
public function __construct()
{
  $this->pluginPath = dirname(__FILE__);
  $this->db_handler = DatabaseHandler::get_instance();

  add_action(\'admin_print_styles\', array($this, \'add_admin_styles\'));
  add_action(\'admin_enqueue_scripts\', array($this, \'add_admin_scripts\'));
  add_action(\'wp_ajax_add_vehicle\', array($this, \'add_vehicle\'));
  add_action(\'wp_ajax_nopriv_add_vehicle\', array($this, \'add_vehicle\'));
}

public function add_admin_scripts()
{
  wp_enqueue_script(\'admin_scripts\', plugins_url(\'js/functions.admin.js\', __FILE__), array(\'jquery\'));
  wp_localize_script(
    \'admin_scripts\',
    \'ajax_object\',
    array(
      \'ajaxurl\' => admin_url(\'admin-ajax.php\'),
      \'nonce\' => wp_create_nonce(\'ajax-nonce\')
    )
  );
}

public function add_vehicle()
{
  // var_dump($_POST);
  // die();

  $nonce = $_POST[\'nonce\'];

  if (!wp_verify_nonce($nonce, \'ajax-nonce\')) {
    die(\'Busted!\');
  }

  //add new vehicle to database
  $this->db_handler->admin_insert_vehicle($_POST[\'vehicle\']);
  $id = $this->db_handler->get_last_insert_id();
  $vehicle = (object) array(
    \'id\' => $id,
    \'description\' => $_POST[\'vehicle\']
  );

  $response = json_encode($vehicle);

  // response output -> sent back to javascript file
  // header("Content-Type: application/json");
  wp_send_json($response);
}
}//end class
$wpPluginAdmin = new PluginAdmin();

EDIT 2:

I did, based on the suggestion in the comments, a complete refactoring and are using the WP REST API from now on.

1 个回复
SO网友:Sabbir Hasan

我注意到你的ajax调用中有一些东西。

$.ajax({
            type: \'POST\',
            url: ajaxurl,
            data: data,
难道不是吗ajax_object.ajaxurl 而不仅仅是ajaxurl ?

相关推荐

在哪里添加我的PHP代码才能让AJAX jQuery工作?

我试图根据从列表中选择的国家(通过图书馆)相应地显示州名。我想我需要使用WP-AJAX和Jquery来实现这个目标。我对WP-AJAX和Jquery完全陌生。在过去的两天里,我一直在阅读博客和论坛,以实现响应能力。在这里,我遇到了两个文件来添加我的PHP代码片段,它们是函数。php和插件文件。Question: 我应该在中添加PHP代码段吗themes/functions.php 或plugins/MYPLUGIN/myplugin.php 或either one? 为什么?我读过的两个博客实例:http