我在自定义的WordPress插件中使用ajax时遇到了“Bad request”错误。

huangapple go评论86阅读模式
英文:

I'm getting "Bad request" using ajax in custom WordPress plugin

问题

I am trying to create a form in my first WordPress app, but the moment I send the Post data using $.ajax() I get the error "Bad request".

我正在尝试在我的第一个WordPress应用程序中创建一个表单,但是当我使用$.ajax()发送Post数据时,我收到"Bad request"错误。

Any help will be really appreciated.

非常感谢任何帮助。

My JS code:

我的JS代码:

jQuery(document).ready(function($) {
    // Verify if my_ajax_obj is defined
    if (typeof my_ajax_obj !== 'undefined') {
        console.log(my_ajax_obj);
        
        // Capture the submit event of the form
        $("#dhl_guias_form").on("submit", function(event) {
            event.preventDefault();
            
            // Serialize form data and convert it to JSON
            var formData = $("#dhl_guias_form").serialize()

            console.log(formData);
    
            // Perform the POST request using $.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) {
                    // Request success
                    console.log(response);
                    console.log("OK");
                },
                error: function(xhr, status, error) {
                    // Request error
                    console.log(error);
                    console.log("error");
                }
            });
        });
    } else {
        console.log("my_ajax_obj is not defined");
    }
});

My PHP code:

我的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
*/

// Activate the plugin
register_activation_hook(__FILE__, 'astral_plugin_activation');

function astral_plugin_activation() {
    // Code to activate the plugin
    global $wpdb;
    $table_name = $wpdb->prefix . 'dhl_guias'; // Table name
    $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);
}

// Deactivate the plugin
register_deactivation_hook(__FILE__, 'astral_plugin_deactivation');

function astral_plugin_deactivation() {
    // Code to deactivate the plugin
}

function astral_create_menu() {
    add_menu_page(
        'Astral',               // Page title
        'Astral Menu',          // Menu title
        'manage_options',       // Capability
        'astral-menu',          // Menu slug
        'astral_menu_callback', // Callback to display menu content
        'dashicons-admin-generic', // Icon
        1                       // Menu position in the admin panel
    );
}

add_action('admin_menu', 'astral_create_menu'); // Create Menu

function astral_menu_callback() {
    // Code to display the Astral menu content
    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'); // Verify nonce for added security

    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(); // End the execution of the AJAX request
}

My form (astral_visual.php):

我的表单(astral_visual.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>
英文:

I am trying to create a form in my first WordPress app, but the moment I send the Post data using $.ajax() I get the error "Bad request".

我在自定义的WordPress插件中使用ajax时遇到了“Bad request”错误。

I tried several solutions, even using Chat GTP, but I can't fix this error.

Any help will be really appreciated.

My JS code:

jQuery(document).ready(function($) {
// Verificar si my_ajax_obj est&#225; definido
if (typeof my_ajax_obj !== &#39;undefined&#39;) {
console.log(my_ajax_obj);
// Capturamos el evento submit del formulario
$(&quot;#dhl_guias_form&quot;).on(&quot;submit&quot;, function(event) {
event.preventDefault();
// Serializamos los datos del formulario y los convertimos en JSON
var formData =  $(&quot;#dhl_guias_form&quot;).serialize()
console.log(formData);
// Realizamos la solicitud POST utilizando $.ajax
jQuery.ajax({
type: &quot;POST&quot;,
url: my_ajax_obj.ajax_url,        
data: formData,
action: &#39;astral_save_form&#39;,
beforesend: function(){
alert(&quot;hello&quot;);
console.log(&quot;ajax&quot;);                    
console.log(my_ajax_obj);
console.log(my_ajax_obj.ajax_url);
},
nonce: my_ajax_obj.nonce,
success: function(response) {
// &#201;xito en la solicitud
console.log(response);
console.log(&quot;OK&quot;);
},
error: function(xhr, status, error) {
// Error en la solicitud
console.log(error);
console.log(&quot;error&quot;);
}
});
});
} else {
console.log(&quot;my_ajax_obj no est&#225; definido&quot;);
}
});

My PHP code:

&lt;?php
/*
Plugin Name: Astral
Plugin URI: https://www.ejemplo.com
Description: Descripci&#243;n del plugin.
Version: 1.0
Author: Tu Nombre
Author URI: https://www.tunombre.com
*/
// Activar el plugin
register_activation_hook(__FILE__, &#39;astral_plugin_activation&#39;);
function astral_plugin_activation() {
// C&#243;digo para activar el plugin
global $wpdb;
$table_name = $wpdb-&gt;prefix . &#39;dhl_guias&#39;; // Nombre de la tabla
$charset_collate = $wpdb-&gt;get_charset_collate();
$sql = &quot;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;&quot;;
require_once(ABSPATH . &#39;wp-admin/includes/upgrade.php&#39;);
dbDelta($sql);
}
// Desactivar el plugin
register_deactivation_hook(__FILE__, &#39;astral_plugin_deactivation&#39;);
function astral_plugin_deactivation() {
// C&#243;digo para desactivar el plugin
}
function astral_create_menu() {
add_menu_page(
&#39;Astral&#39;,               // T&#237;tulo de la P&#225;gina
&#39;Astral Menu&#39;,          // T&#237;tulo del Men&#250;
&#39;manage_options&#39;,       // Capability
&#39;astral-menu&#39;,          // Slug del Men&#250;
&#39;astral_menu_callback&#39;, // Callback para mostrar el contenido del men&#250;
&#39;dashicons-admin-generic&#39;, // Icono
1                       // Posici&#243;n del men&#250; en el panel de administraci&#243;n
);
}
add_action(&#39;admin_menu&#39;, &#39;astral_create_menu&#39;); // Crear Men&#250;
function astral_menu_callback() {
// C&#243;digo para mostrar el contenido del men&#250; Astral
include plugin_dir_path(__FILE__) . &#39;astral_visual.php&#39;;
}
add_action( &#39;admin_enqueue_scripts&#39;, &#39;my_enqueue&#39; );
function my_enqueue( $hook ) {
if ( &#39;toplevel_page_astral-menu&#39; !== $hook ) {
return;
}
wp_enqueue_script(
&#39;ajax-script&#39;,
plugins_url( &#39;js/astral.js&#39;, __FILE__ ),
array( &#39;jquery&#39; ),
);
$title_nonce = wp_create_nonce( &#39;title_example&#39; );
wp_localize_script(
&#39;ajax-script&#39;,
&#39;my_ajax_obj&#39;,
array(
&#39;ajax_url&#39; =&gt; admin_url( &#39;admin-ajax.php&#39; ),
&#39;nonce&#39;    =&gt;wp_create_nonce( &#39;nonce&#39; )
)
);
}
add_action(&#39;wp_ajax_astral_save_form&#39;, &#39;astral_save_form&#39;);
function astral_save_form() {
check_ajax_referer(&#39;astral_ajax_nonce&#39;, &#39;nonce&#39;); // Verificar el nonce para mayor seguridad
global $wpdb;
$table_name = $wpdb-&gt;prefix . &#39;dhl_guias&#39;;
$field1 = sanitize_text_field($_POST[&#39;field1&#39;]);
$field2 = sanitize_text_field($_POST[&#39;field2&#39;]);
$wpdb-&gt;insert(
$table_name,
array(
&#39;id&#39; =&gt; NULL,
&#39;nombre&#39; =&gt; $field1,
&#39;direccion&#39; =&gt; $field2
)
);
wp_die(); // Finaliza la ejecuci&#243;n de la solicitud AJAX
}

My form (astral_visual.php):

&lt;form id=&quot;dhl_guias_form&quot; method=&quot;POST&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;field1&quot; placeholder=&quot;Campo 1&quot; /&gt;&lt;br&gt;
&lt;input type=&quot;text&quot; name=&quot;field2&quot; placeholder=&quot;Campo 2&quot; /&gt;&lt;br&gt; 
&lt;button type=&quot;submit&quot; id=&quot;save&quot; name=&quot;save&quot;&gt;GUARDAR&lt;/button&gt;
&lt;/form&gt;

答案1

得分: 0

你的代码中有一些错误和问题。

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

PHP主要插件代码:

<?php
/*
插件名称:Astral
插件URI:https://www.example.com
描述:插件描述。
版本:1.0
作者:你的名字
作者URI:https://www.yourname.com
*/

// 插件激活 - 在数据库中创建'dhl_guias'表
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()}");
}

// 插件停用
register_deactivation_hook(__FILE__, 'astral_plugin_deactivation');
function astral_plugin_deactivation() {
    // 你的代码
}

// 在WordPress管理中添加菜单
add_action('admin_menu', 'astral_create_menu'); 
function astral_create_menu() {
    add_menu_page(
        'Astral',               // 页面标题
        'Astral菜单',          // 菜单标题
        'manage_options',       // 权限
        'astral-menu',          // 菜单别名
        'astral_menu_callback', // 用于内容输出的函数
        'dashicons-admin-generic', // 图标
        1                       // 在管理菜单中的位置
    );
}

// 菜单回调函数
function astral_menu_callback() {
    // 显示内容的代码(调用外部文件)
    include plugin_dir_path(__FILE__) . 'astral_visual.php';
}

// 注册JavaScript外部文件
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() {
    // 检查Ajax请求以防止外部不安全的请求
    check_ajax_referer('astral_nonce', 'security'); 

    global $wpdb;

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

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

            // 在数据库中插入一些数据
            $wpdb->insert( "{$wpdb->prefix}dhl_guias",  array(
                'id' => NULL,
                'nombre' => sanitize_text_field($data['fullname']),
                'direccion' => sanitize_text_field($data['address'])
            ) );
            echo "成功!数据已保存到数据库中";
        } else {
            echo "警告:未填写某些表单字段";
        }
    } else {
        echo "警告:未发送表单数据";
    }
    wp_die(); // 静默结束(必需的)
}

HTML表单(添加到astral_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 astral.js外部文件:

jQuery( function($) {
    // 检查是否定义了本地化变量astral_params
    if (typeof astral_params !== 'undefined') {
        console.log(astral_params);
        
        // 在提交表单事件上
        $('form#dhl-guias').on('submit', function(e) {
            e.preventDefault(); // 阻止默认表单提交行为
            
            // 序列化表单数据
            var formData =  $(this).serialize()

            // 通过Ajax发送POST请求
            $.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); // 添加消息

                    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"未定义');
    }
});

经过测试,当填写表单时,会将条目添加到数据库表中。

英文:

There are some mistakes and errors in your code.

Note: As Stack Overflow is an English-speaking community, I have translated mostly everything.

The PHP main plugin code:

&lt;?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 &#39;dhl_guias&#39; table in database
register_activation_hook(__FILE__, &#39;astral_plugin_activation&#39;);
function astral_plugin_activation() {
    require_once(ABSPATH . &#39;wp-admin/includes/upgrade.php&#39;);

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

// Plugin deactivation
register_deactivation_hook(__FILE__, &#39;astral_plugin_deactivation&#39;);
function astral_plugin_deactivation() {
    // your code
}

// Add a menu in the WordPress admin
add_action(&#39;admin_menu&#39;, &#39;astral_create_menu&#39;); 
function astral_create_menu() {
    add_menu_page(
        &#39;Astral&#39;,               // Page title
        &#39;Astral Menu&#39;,          // Menu title
        &#39;manage_options&#39;,       // Capability
        &#39;astral-menu&#39;,          // Menu slug
        &#39;astral_menu_callback&#39;, // The function to be called for content output
        &#39;dashicons-admin-generic&#39;, // 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__) . &#39;astral_visual.php&#39;;
}

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

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

   wp_localize_script(
      &#39;astral-ajax-script&#39;,
      &#39;astral_params&#39;,
      array(
         &#39;ajax_url&#39; =&gt; admin_url( &#39;admin-ajax.php&#39; ),
         &#39;nonce&#39;    =&gt; wp_create_nonce( &#39;astral_nonce&#39; )
      )
   );
}

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

    global $wpdb;

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

        if( isset($data[&#39;fullname&#39;])  &amp;&amp; isset($data[&#39;address&#39;])
        &amp;&amp; ! empty($data[&#39;fullname&#39;]) &amp;&amp; ! empty($data[&#39;address&#39;]) ) {

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

The HTML form (added to astral_visual.php external file):

&lt;form id=&quot;dhl-guias&quot; method=&quot;POST&quot;&gt;
    &lt;label for=&quot;fullname&quot;&gt;Nombre completo:&lt;/label&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;fullname&quot; name=&quot;fullname&quot; placeholder=&quot;Agrega tu nombre completo aqu&#237;&quot; /&gt;&lt;br&gt;
    &lt;label for=&quot;address&quot;&gt;Direcci&#243;n:&lt;/label&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;address&quot; name=&quot;address&quot; placeholder=&quot;A&#241;ade tu direcci&#243;n aqu&#237;&quot; /&gt;&lt;br&gt;&lt;br&gt;
    &lt;button type=&quot;submit&quot; id=&quot;save&quot; name=&quot;save&quot;&gt;Guardar&lt;/button&gt;&lt;br&gt;
    &lt;p class=&quot;message&quot;&gt;&lt;/p&gt;
&lt;/form&gt;

The jQuery / JavaScript astral.js external file

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

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

                    console.log(&quot;success&quot;);
                    console.log(response);
                },
                error: function(xhr, status, error) {
                    console.log(&quot;error&quot;);
                    console.log(xhr);
                    console.log(error);
                }
            });
        });
    } else {
        console.log(&#39;&quot;astral_params&quot; is not defined&#39;);
    }
});

Tested and works. When the form is filled, an entry is added to the database table.

huangapple
  • 本文由 发表于 2023年7月7日 06:13:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定