使用Ajax处理PHP错误

时间:2014-04-05 17:30:24

标签: php jquery ajax

尝试通过ajax提交表单并处理PHP错误,

这是我的表格

<div class="boxFocus">
   <?php echo $message_text;  echo $errors;  ?>
   <form method="post" action="<?php bloginfo('template_directory'); ?>/includes/form-handler.php" id="contactfrm" role="form">
      <div class="form-group">
         <label for="name">Name</label>
         <input type="text" class="form-control" name="name" id="name" placeholder="Enter name"  title="Please enter your name (at least 2 characters)" required/>
      </div>
      <div class="form-group">
         <label for="email">Email</label>
         <input type="email" class="form-control" name="email" id="email" placeholder="Enter email" title="Please enter a valid email address"/>
      </div>
      <div class="form-group">
         <label for="phone">Phone</label>
         <input name="phone" class="form-control required digits" type="tel" id="phone" size="30" value="" placeholder="Enter email phone" title="Please enter a valid phone number (at least 10 characters)" required>
      </div>
      <div class="form-group">
         <label for="comments">Comments</label>
         <textarea name="message" class="form-control" id="comments" cols="3" rows="5" placeholder="Enter your message…" title="Please enter your message (at least 10 characters)" required></textarea>
      </div>
      <div class="result"></div>
      <button name="submit" type="submit" class="btn btn-primary" id="submitform"> Submit</button>
   </form>
   <div class="result"></div>
</div>

这是jQuery

 $("#submitform").click(function(){
   // e.preventDefault();
    //alert("yo");
    var form_data = $("#contactfrm").serialize();
    $.ajax({
        type: "POST",
        url: "/ltlcreation-new/wordpress/wp-content/themes/LTLCreation/includes/form-handler.php",
        data: form_data,
        error: function(){
            alert("failed");
        },
        success: function(){
            alert("success");
        },
        })
    });

这是表单处理程序

<?php


if(isset($_POST['submit'])) {

  //include validation class
  include 'validate.class.php';

  //assign post data to variables
  $name = @($_POST['name']);
  $email = @($_POST['email']);
  $message = @($_POST['message']);
  $phone = @$_POST["phone"];

  //echo $name, $email, $message, $phone;


  //start validating our form
  $v = new validate();
  $v->validateStr($name, "name", 3, 75);
  $v->validateEmail($email, "email");
  $v->validateStr($message, "message", 5, 1000);
  $v->validateStr($phone, "phone", 11, 13);

  if(!$v->hasErrors()) {

        $to = "lukelangfield001@googlemail.com";
        $subject = "Website contact form ";

        $mailbody = $message . "\n" . "from " . $name . "\n" . $phone;
        $headers = "From: $email";

        mail($to, $subject, $mailbody, $headers);

        echo "success";

    } else {
    //set the number of errors message
    $message_text = $v->errorNumMessage();

    //store the errors list in a variable
    $errors = $v->displayErrors();

    //get the individual error messages
    $nameErr = $v->getError("name");
    $emailErr = $v->getError("email");
    $messageErr = $v->getError("message");
    $phoneErr = $v->getError("phone");

   echo $message_text;  echo $errors;  
  }//end error check

}// end isset

当我在没有Ajax的情况下触发表单处理程序时,它正常工作并返回验证错误,我想知道如何将这些传递回页面并更新内容以显示错误。警报仅适用于我尝试使用Ajax的时候,将来我会用结果更新div类结果

很抱歉,如果这是一个基本问题,我只是努力想要了解ajax,因为之前我一直在使用malsup,但我想自己这样做。

3 个答案:

答案 0 :(得分:1)

您没有预期的结果,因为您正在发送表单。

你必须在&#34;点击&#34;中使用event参数。功能并防止默认行为,即发送表单。 简单版本的代码可能如下所示:

   $("#submitform").click(function(e) {
     e.preventDefault();
     window.console.log('will not submit a form');
     // ajax request
   });

您的代码应如下所示:

   $("#submitform").click(function(e){
     e.preventDefault();

     var form_data = $("#contactfrm").serialize();
     $.ajax({
        type: "POST",
        url: "/ltlcreation-new/wordpress/wp-content/themes/LTLCreation/includes/form-handler.php",
        data: form_data,
        error: function(){
            alert("failed");
        },
        success: function(){
            alert("success");
        },
        })
    });

答案 1 :(得分:0)

您可以通过更改success回调来检查返回数据的内容,例如......

success: function(response){
    console.log(response);
    //do stuff here like add messages in your <div>
},

检查实际输出后,也许您可​​以更新您的问题,以便查看并帮助您更多地了解输出。

答案 2 :(得分:0)

我可以将你的PHP片段包装在try / catch块中,如果PHP失败,你总是可以在你想要的HTML中包含一个错误并将其返回给浏览器。