我正试图在我的第一个WordPress应用程序中创建一个表单,但当我使用$.ajax()发送Post数据的那一刻,我收到错误消息"Bad Request".

Bad request received screenshot

我try 了几种解决方案,甚至使用Chat GTP,但我无法修复此错误.

任何帮助都将不胜感激.

我的JS代码:

jQuery(document).ready(function($) {
    // Verificar si my_ajax_obj está definido
    if (typeof my_ajax_obj !== 'undefined') {
        console.log(my_ajax_obj);
        
        // Capturamos el evento submit del formulario
        $("#dhl_guias_form").on("submit", function(event) {
            event.preventDefault();
            
            // Serializamos los datos del formulario y los convertimos en JSON
            var formData =  $("#dhl_guias_form").serialize()

            console.log(formData);
    
         
            
      
          
            // Realizamos la solicitud POST utilizando $.ajax
            jQuery.ajax({

                type: "POST",
            
                url: my_ajax_obj.ajax_url,        
                
                data: formData,
                action: 'astral_save_form',
                beforesend: function(){
                    alert("hello");
                    console.log("ajax");                    
                    console.log(my_ajax_obj);
                    console.log(my_ajax_obj.ajax_url);
                },
                nonce: my_ajax_obj.nonce,
                
               
                success: function(response) {
                    // Éxito en la solicitud
                    console.log(response);
                    console.log("OK");
                },
                error: function(xhr, status, error) {
                    // Error en la solicitud
                    console.log(error);
                    console.log("error");
                }
            });
        });
    } else {
        console.log("my_ajax_obj no está definido");
    }
});

我的PHP代码:

<?php
/*
Plugin Name: Astral
Plugin URI: https://www.ejemplo.com
Description: Descripción del plugin.
Version: 1.0
Author: Tu Nombre
Author URI: https://www.tunombre.com
*/

// Activar el plugin
register_activation_hook(__FILE__, 'astral_plugin_activation');

function astral_plugin_activation() {
    // Código para activar el plugin
    global $wpdb;
    $table_name = $wpdb->prefix . 'dhl_guias'; // Nombre de la tabla
    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE $table_name (
        id INT NOT NULL AUTO_INCREMENT,
        nombre VARCHAR(100) NOT NULL,
        direccion VARCHAR(100) NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

// Desactivar el plugin
register_deactivation_hook(__FILE__, 'astral_plugin_deactivation');

function astral_plugin_deactivation() {
    // Código para desactivar el plugin
}


function astral_create_menu() {
    add_menu_page(
        'Astral',               // Título de la Página
        'Astral Menu',          // Título del Menú
        'manage_options',       // Capability
        'astral-menu',          // Slug del Menú
        'astral_menu_callback', // Callback para mostrar el contenido del menú
        'dashicons-admin-generic', // Icono
        1                       // Posición del menú en el panel de administración
    );
}

add_action('admin_menu', 'astral_create_menu'); // Crear Menú

function astral_menu_callback() {
    // Código para mostrar el contenido del menú Astral
    include plugin_dir_path(__FILE__) . 'astral_visual.php';
}

add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue( $hook ) {
   if ( 'toplevel_page_astral-menu' !== $hook ) {
      return;
   }

   wp_enqueue_script(
      'ajax-script',
      plugins_url( 'js/astral.js', __FILE__ ),
      array( 'jquery' ),
      
   );

   $title_nonce = wp_create_nonce( 'title_example' );
   wp_localize_script(
      'ajax-script',
      'my_ajax_obj',
      array(
         'ajax_url' => admin_url( 'admin-ajax.php' ),
         'nonce'    =>wp_create_nonce( 'nonce' )
         
      )
   );
}

add_action('wp_ajax_astral_save_form', 'astral_save_form');

function astral_save_form() {
    check_ajax_referer('astral_ajax_nonce', 'nonce'); // Verificar el nonce para mayor seguridad

    global $wpdb;
    $table_name = $wpdb->prefix . 'dhl_guias';

    $field1 = sanitize_text_field($_POST['field1']);
    $field2 = sanitize_text_field($_POST['field2']);

    $wpdb->insert(
        $table_name,
        array(
            'id' => NULL,
            'nombre' => $field1,
            'direccion' => $field2
        )
    );

    wp_die(); // Finaliza la ejecución de la solicitud AJAX
}

我的表单(astal_visal.php):

<form id="dhl_guias_form" method="POST">
    <input type="text" name="field1" placeholder="Campo 1" /><br>
    <input type="text" name="field2" placeholder="Campo 2" /><br> 
    <button type="submit" id="save" name="save">GUARDAR</button>
</form>

推荐答案

代码中存在一些错误和错误.

注:由于Stack Overflow是一个讲英语的社区,我已经翻译了大部分内容.

PHP主插件代码:

<?php
/*
Plugin Name: Astral
Plugin URI: https://www.example.com
Description: Plugin description.
Version: 1.0
Author: Your name
Author URI: https://www.yourname.com
*/

// Plugin activation - Create 'dhl_guias' table in database
register_activation_hook(__FILE__, 'astral_plugin_activation');
function astral_plugin_activation() {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    global $wpdb;
    
    dbDelta("
        CREATE TABLE {$wpdb->prefix}dhl_guias (
        id INT NOT NULL AUTO_INCREMENT,
        nombre VARCHAR(100) NOT NULL,
        direccion VARCHAR(100) NOT NULL,
        PRIMARY KEY (id)
    ) {$wpdb->get_charset_collate()}");
}

// Plugin deactivation
register_deactivation_hook(__FILE__, 'astral_plugin_deactivation');
function astral_plugin_deactivation() {
    // your code
}

// Add a menu in the WordPress admin
add_action('admin_menu', 'astral_create_menu'); 
function astral_create_menu() {
    add_menu_page(
        'Astral',               // Page title
        'Astral Menu',          // Menu title
        'manage_options',       // Capability
        'astral-menu',          // Menu slug
        'astral_menu_callback', // The function to be called for content output
        'dashicons-admin-generic', // Icon
        1                       // Position in the Admin menu order
    );
}

// Function called by the menu
function astral_menu_callback() {
    // Code to display the content (calling an external file)
    include plugin_dir_path(__FILE__) . 'astral_visual.php';
}

// Register JavaScript external files
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue( $hook ) {
   if ( 'toplevel_page_astral-menu' !== $hook ) {
      return;
   }

    wp_enqueue_script( 'astral-ajax-script', 
        plugins_url( 'js/astral.js', FILE ), 
        array( 'jquery' ),'1.0.0', true ); 

   wp_localize_script(
      'astral-ajax-script',
      'astral_params',
      array(
         'ajax_url' => admin_url( 'admin-ajax.php' ),
         'nonce'    => wp_create_nonce( 'astral_nonce' )
      )
   );
}

add_action('wp_ajax_astral_save_form', 'astral_save_form');
function astral_save_form() {
    // Check the Ajax request to prevent external insecure requests
    check_ajax_referer('astral_nonce', 'security'); 

    global $wpdb;

    if( isset($_REQUEST['form_data'])) {
        $data = array(); // initializing
        parse_str($_REQUEST['form_data'], $data);  

        if( isset($data['fullname'])  && isset($data['address'])
        && ! empty($data['fullname']) && ! empty($data['address']) ) {

            // Inserting the some data in the database
            $wpdb->insert( "{$wpdb->prefix}dhl_guias",  array(
                'id' => NULL,
                'nombre' => sanitize_text_field($data['fullname']),
                'direccion' => sanitize_text_field($data['address'])
            ) );
            echo "Success! The data has been saved to the database";
        } else {
            echo "Warning: Some form fields have not been filled";
        }
    } else {
        echo "Warning: The form data has not ben sent";
    }
    wp_die(); // End silently (mandatory)
}

HTML表单(添加到Asteral_Visual.php外部文件):

<form id="dhl-guias" method="POST">
    <label for="fullname">Nombre completo:</label><br>
    <input type="text" id="fullname" name="fullname" placeholder="Agrega tu nombre completo aquí" /><br>
    <label for="address">Dirección:</label><br>
    <input type="text" id="address" name="address" placeholder="Añade tu dirección aquí" /><br><br>
    <button type="submit" id="save" name="save">Guardar</button><br>
    <p class="message"></p>
</form>

JQuery/JAVASCRIPT ASTAL.js外部文件

jQuery( function($) {
    // check that the localized variable astral_params is defined
    if (typeof astral_params !== 'undefined') {
        console.log(astral_params);
        
        // On submitting the form event
        $('form#dhl-guias').on('submit', function(e) {
            e.preventDefault(); // Stop default form post action
            
            // Serializing form data
            var formData =  $(this).serialize()

            // Sending the post request via Ajax
            $.ajax({
                type: "POST",
                url: astral_params.ajax_url,
                datatype: 'json',
                data: { 
                    'action': 'astral_save_form',
                    'form_data': formData,
                    'security': astral_params.nonce
                },
                beforesend: function( xhr ){
                    console.log("beforesend");
                    console.log(xhr);                    
                },
                success: function(response) {
                    $('form p.message').html(response); // add a message

                    console.log("success");
                    console.log(response);
                },
                error: function(xhr, status, error) {
                    console.log("error");
                    console.log(xhr);
                    console.log(error);
                }
            });
        });
    } else {
        console.log('"astral_params" is not defined');
    }
});

经过测试,效果良好.填写表单后,将在数据库表中添加一个条目.

Jquery相关问答推荐

如何在不使用点击事件 bootstrap 程序模式的情况下使用弹出窗口 bootstrap 程序显示用户详细信息?

子 li 元素的点击事件

Sheets从多张sheet中导入range匹配数据

jQuery找到最近的匹配元素

使用 jQuery / javascript 测试链接是否是外部的?

jQuery / Ajax - $.ajax() 将参数传递给回调 - 使用好的模式?

如何在 jquery 中包含 !important

使用 jQuery,当用户仍在编辑该字段时,如何将文本字段的第一个字母大写?

jQuery增量读取AJAX流?

如何使用 Twitter Bootstrap 弹出框进行 jQuery 验证通知?

我可以限制 JavaScript 中数组的长度吗?

如何使用 Twitter Bootstrap 自动关闭alert

测试两个元素是否相同

删除 Javascript 中的所有多个空格并替换为单个空格

jQuery - 从元素内部 Select 元素

jQuery select2 获取 Select 标签的值?

Chrome 中的 AJAX 发送选项而不是 GET/POST/PUT/DELETE?

在 Firefox 上开发的 Javascript 在 IE 上失败的典型原因是什么?

$(document).click() 在 iPhone 上无法正常工作. jQuery

小于 10 给数字加 0