【问题标题】:How to use php validation in ajax request in wordpress?如何在wordpress的ajax请求中使用php验证?
【发布时间】:2021-08-28 11:07:20
【问题描述】:

我制作了一个使用AJAX 发送消息的联系表单(自定义)。现在我不清楚如何验证表单。

AJAX 请求:

  $("#contact-form").on("submit", function (e) {
    e.preventDefault();
    var action = "contact_form";

    $("#submit, #clear").prop("disabled", true);
    $("#submit").html("Sending");

    $.ajax({
      url: $(this).attr("action"),
      method: "post",
      data: {
        name: $("#name").val(),
        email: $("#email").val(),
        phone: $("#phone").val(),
        subject: $("#subject").val(),
        message: $("#message").val(),
        action: action,
      },

      success: function () {
        $("header").append(
          "<div id='alert' class='alert alert-success alert-dismissible fixed-top' role='alert' >" +
            "<p class='text-center'>Success</p>" +
            "<button type = 'button' class='close' data-dismiss = 'alert'>&times;</button>" +
            "</div>"
        );
        $("#submit, #clear").prop("disabled", false);
        // $("#contact-form input,textarea").val("");
        grecaptcha.reset();
        $("#submit").html("Send");
      },
      error: function () {
        $("header").append(
          "<div id='alert' class='alert alert-danger alert-dismissible fixed-top' role='alert' >" +
            "<p class='text-center'>Error</p>" +
            "<button type = 'button' class='close' data-dismiss = 'alert'>&times;</button>" +
            "</div>"
        );
        $("#submit, #clear").prop("disabled", false);
        grecaptcha.reset();
        $("#submit").html("Send");
      },
    });
  });
});

函数.php:

function contact_form()  // this is the action data variable we set in ajax
{
 

   $name         = $_POST['name'];
   $email        = $_POST['email'];
   $phone        = $_POST['phone'];
   $subject = $_POST['subject'];
   $message  = $_POST['message'];
 
   // preparing parameters for wp_mail();
   $to      = "mail@example.com";
      $msg     = "
   Name: $name
   Email: $email
   Phone: $phone
    
   $message
   ";
   

   // sending mail using wp_mail function
    wp_mail($to, $subject, $msg);
       

    wp_die(); // must use wp_die() to avoid unwanted output from wordpress
}

// in first parameter prefix function name with wp_ajax_ 
// this action is required in order to recieve data sent from ajax 
add_action( 'wp_ajax_contact_form', 'contact_form' );
add_action( 'wp_ajax_nopriv_contact_form', 'contact_form' );

现在,当我不尝试使用 ajax 时,我通常会在 php 文件中进行预执行验证,例如,如果验证码无效,我会将状态附加到 GET 方法并返回错误。如果有人能指出我如何在 php 文件中进行验证并将信息返回到前端,或者我应该在 js 文件中进行验证吗?我很困惑,网上有这么多文章,我真的不知道在哪里看。
P.S 一切正常,只需验证它。

【问题讨论】:

    标签: php jquery ajax wordpress forms


    【解决方案1】:

    验证两种方式。 JS 验证可提供流畅的用户体验,并解决有关有效电子邮件地址、非空字段等的大多数问题。

    PHP 验证将确保您的函数不会出错,并且可以让您进行一些服务器端检查(例如之前没有发送过确切的消息等)

    在 php 中,进行验证检查并准备任何错误的 json 响应,然后在出现错误时回显(而不是继续执行代码)。在 JS 中捕获成功块中的错误 - 现在它不会监听任何响应。

    PHP:

    if ($errors) {
      echo json_encode(array('status' => 'error', 'message' => 'Your email message has objectionable content'));
      wp_die();
    }
    
    if (!wp_mail($to, $subject, $msg)) {
       echo json_encode(array('status' => 'error', 'message' => 'Your email message did not send for some reason'));
      wp_die();
    }
    
    echo json_encode(array('status' => 'success');
    wp_die();
    

    你的 JS

    // ajax...
    $.ajax({
       ... your props
      dataType: 'json',
      success: function (response) {
        if (response && response.status == 'error'){
          $('errors').html("Sorry, your message did not get sent due to these errors: " + response.message);
         return;
        } else {
          // .. success
         
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 2018-01-24
      • 1970-01-01
      相关资源
      最近更新 更多