【问题标题】:How to fix ajax request to the form handler file from the WordPress plugin. (I am developing a plugin myself)如何从 WordPress 插件修复对表单处理程序文件的 ajax 请求。 (我正在自己开发一个插件)
【发布时间】:2020-09-06 07:25:33
【问题描述】:

大家!我正在创建 WordPress 插件。该插件的主要目标是创建表单,用户填写此表单后,表单中的数据将写入数据库。我制作了插件的一部分,负责创建数据库并使用简码显示表单。但面临一个问题。如何使用 ajax 方法将数据从表单发送到数据库。

激活插件后,在数据库中创建一个表:

if ( ! function_exists ( 'jal_install' ) ) {
function jal_install (){
    global $wpdb;
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    $table_name = $wpdb->prefix . "liveshoutbox";
    $charset_collate = $wpdb->get_charset_collate();
        if($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") !== $table_name){
            $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,

            client_name tinytext NOT NULL,
            client_mail varchar(55) DEFAULT '' NOT NULL,

            PRIMARY KEY  (id)
            ) $charset_collate;";
        dbDelta( $sql );
    }   
  }
}

页面上的表单以简码显示:

function form_shortcode() {
        ob_start(); ?>

      <form class="main_form" method="POST" action="">
            <input type="text" name="user_name">
            <input type="text" name="user_mail">
            <button type="submit">Subnit</button>
      </form>
      <div class="main_form__success">Greate Worck!</div>
         
    <?php 
      return ob_get_clean();
    }

    add_shortcode('form-shortcode', 'form_shortcode');

为了将表单中的数据添加到数据库中,有一个文件:form_action.php 我把它放在主插件目录下。为了启动这个文件的工作,我使用了 form_ajax.js

$("form.main_form").submit(function() {
      var th = $(this);
      $.ajax({
        type: "POST",
        url: "/form_action.php",
      }).done(function() {
        $(th).find('.main_form__success').addClass('active').css('display', 'flex').hide().fadeIn();
        setTimeout(function() {
          $(th).find('.main_form__success').removeClass('active').fadeOut();
          th.trigger("reset");
        }, 3000);
      });
      return false;
    });

因此,我无法访问此 form_action.php 文件。我有一个错误。该代码试图在站点的根目录中找到它,但不在插件的根目录中。我不明白如何解决它,请告诉我该怎么做。

【问题讨论】:

  • 你的form_action.php在同一个目录吗?
  • @SandrinJoy 插件根文件夹中没有 form_action.php。以及公开的js文件-js-plugin.js
  • 我已经修改了我的网址,请验证

标签: php jquery ajax wordpress


【解决方案1】:

这是 ajax jquery 请求的基本语法

在这里,在数据字段中,您必须使用 id、name 或 tag 指定您的表单

$.ajax({
  url: "/../form_action.php",
  type: "POST",
  data:$('form').serialize(),
  success: function (data) {
    .....
  }
});

【讨论】:

  • 谢谢,但是 ajax 请求工作正常,它根本找不到文件 form_action.php 的路径。这是主要问题。我无法将插件文件放在站点的根目录下。我需要它位于插件的根目录。但是url:“form_action.php”,并没有指向插件目录,而是指向了项目的根目录。
  • 请指定插件的路径,你要根据它编辑url
  • 很遗憾,这个选项不起作用。这是我在控制台中看到的:starating/form_action.php 404 (Not Found)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多