简体   繁体   中英

Bootstrap Contact Form with jQuery Validation and AJAX

I have a simple bootstrap contact form that I'm trying to implement with AJAX and jQuery validation. I feel like I'm pretty close but there are a few things that I can't get to work quite right. The forms validate according to input (ideally I'd like the phone number to be validated as digits; however, I'm new to contact form validation), but the contact form will still send even if the answers are not correct. In addition, the success box will always pop up after the form submits ... I'd like the form to not send if it is filled out incorrectly, and an error box to appear instead of the success. In addition, the email sends through the body of the message, but none of the variables get sent over. So the body of my message looks like:
Name:
Email:
Phone:
Message:

With no variable appear after each.

I know this may be something simple but I'm very new to form validation and I can't figure it out for the life of me.

Here's the HTML for the form:

<div class="form-group wow fadeInRight" data-wow-delay="1s">
  <div class="controls">
    <div class="input-group">
      <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
      <input type="text" class="form-control" id="name" name="name" placeholder="Name" />
    </div>
  </div>
</div>

<div class="form-group wow fadeInRight" data-wow-delay="1.1s">
  <div class="controls">
    <div class="input-group">
      <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
      <input type="text" class="form-control" id="email" name="email" placeholder="Email" />
    </div>
  </div>  
</div>

<div class="form-group wow fadeInRight" data-wow-delay="1.2s">
  <div class="controls">
    <div class="input-group">
      <span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>
      <input type="text" class="form-control" id="phone" name="phone" placeholder="Phone" />
    </div>
  </div>
</div>

<div class="form-group wow fadeInRight" data-wow-delay="1.3s">
  <div class="controls">
    <div class="input-group">
      <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
      <textarea name="message" class="form-control " rows="4" cols="78" placeholder="Enter your message here."></textarea>
    </div>
  </div>
</div>

<div id="success"></div>
<div class="row wow fadeInUp" data-wow-delay="1.3s">
  <div class="form-group col-xs-12">
    <div class="contact-btns">
      <input type="submit" class="submit-button" value="Submit" name="submit">
      <input type="reset" class="clear-buttom" value="Clear" name="clear">
    </div>
  </div>
</div>

</form>

Here's the PHP:

$status = array(
    'type' => 'success',
    'message' => 'Email sent!'
);

$val = $_POST['val'];
$toemail = 'myemail@gmail.com';
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$msg = $_POST['message'];

$subject = 'Thelliotgroup Information Request';

$headers = "From: Thelliotgroup Website :: " . $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

$message = "<b>Name: </b>" . $name . "<br>";
$message .='<b>Email: </b>' . $email . "<br>";
$message .='<b>Phone: </b>' . $phone . "<br>";
$message .='<b>Message: </b>' . $msg;

$success = mail($toemail, $subject, $message, $headers);

echo json_encode($status);
die

Here's the AJAX and jQuery:

var form = $('.contact');
form.submit(function () {
    $this = $(this);
    $.post($(this).attr('action'), function (data) {
        $this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
    }, 'json');
    return false;
});


$.validator.setDefaults({
    submitHandler: function (form) {
        $.ajax({
            type: "POST",
            url: "email.php",
            data: {'val': $(".contact").serializeJSON()}
        }).done(function (data) {
            alert(data);
        });
    }
});

$(".contact").validate(
        {rules:
                    {name: "required",
                        email: {required: true, email: true},
                        phone: "required",
                        message: {required: true, maxlength: 300
                        }},
            errorClass: "error",
            highlight: function (label) {
                $(label).closest('.form-group').removeClass('has-success').addClass('has-error');
            },
            success: function (label) {
                label
                        //.text('Seems Perfect!').addClass('valid')
                        .closest('.form-group').addClass('has-success');
            }
        });

I'd really appreciate any help you guys could give me to get this working properly.

Edit Here's the new jQuery and AJAX code:

$(document).ready(function() {
var form = $(this); 
var post_url = form.attr('action'); 
$('.contact').validate({ 
    rules: {
        name: {
            rangelength: [2,40], 
            required: true
        },
        email: {
            rangelength: [2,40], 
            email: true,
            required: true
        },
        phone: {
            rangelength: [7,10],
            required: true
        },
        message: {
            minlength: 30,
            required: true
        },
        errorClass:"error",
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-success').addClass('has-error');
        },

        success: function(label) {
            label
            .closest('.form-group').addClass('has-success');
        }
    },
    submitHandler: function(form) { 
        $.ajax({
            type: 'POST',
            url: 'email.php',
            data: $(form).serialize(),
            success: function(msg) {
                $('.sent').fadeIn().fadeOut(5000);
            }
        });            
        return false; 
    }                  
});                    

});

Now I just need to figure out how to make it so that:

<div class="status alert alert-success" style="display: none"></div>

Which is located directly above the form, will fade in once the form is submitted. I can't get it to work.

Thanks, Brennan

I do not understand why you're doing a .post() (ajax) inside of a jQuery submit handler function while at the exact same time you have .ajax() inside of the plugin's submitHandler function. I don't get it. Why are you using ajax twice?

I think it's best that you remove this entire function...

form.submit(function () {
    $this = $(this);
    $.post($(this).attr('action'), function(data) {
        $this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
    },'json');
    return false;
});

Because it is interfering with the plugin's submitHandler function.

Use the submitHandler to fire code upon the button click when the form is valid. This is where any ajax would belong .


EDIT :

You've put errorClass , highlight and success inside the rules option...

rules: {
    name: {
        ....
    },
    email: {
        ....
    },
    phone: {
        ....
    },
    message: {
        ....
    },
    errorClass:"error",
    highlight: function(label) {
        ....        
    },
    success: function(label) {
        ....
    }
},

This is wrong . errorClass , highlight and success are siblings of the rules and submitHandler options.

Also, when using highlight , it's best to use unhighlight along with it to undo whatever you did with highlight .

rules: {
    // only your rules here
},
errorClass:"error",
highlight: function(element) {
    $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element) {
    $(element).closest('.form-group').addClass('has-success').removeClass('has-error');
},
submitHandler: function(form) { 
    $.ajax({
        // your options
    });            
    return false; 
}

For clearing out the form within the Ajax success option...

$('#myform').validate().resetForm(); // reset validation
form[0].reset();                     // clear out the form data             

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