简体   繁体   中英

Handling PHP erros with Ajax

Trying to submit a form via ajax and handle the PHP errors,

here is my form

<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>

Here is the 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");
        },
        })
    });

and here is the form handler

<?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

When I fire the form-handler without Ajax it works correctly and returns me the validation errors, I wanted to know how I can pass these back through to the page and update the content to display the errors. The alerts were just for when I was attempting to use Ajax, in the future I will update the div class result with the result

Sorry if this is a basic question, just struggling to get my head around ajax as previously I've been using malsup but wanted to do this myself.

You don't have expected result, because you're sending the form.

You have to use the event parametr in "on-click" function and prevent a default behaviour ie sending form. Simple version of code may look like this:

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

Your code should look like this:

   $("#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");
        },
        })
    });

You could check the contents of the returned data by changing your success callback like...

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

Once you have checked the actual output, maybe you can update your question for us to see and help you more with the output.

我可以将PHP代码段包装在try / catch块中,如果PHP失败,则始终可以将错误包装在所需的HTML中,然后将其返回到浏览器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM