-1

I am trying to use ajax and jQuery to process a form, fade out the form and then fade in with a success or error message. Unfortunately for some reason the form is still submitting normally instead of using ajax. I am using the jQuery validation plugin to validate the form. Here is the code.

HTML

<form name="contact" id="contact" method="post" >
          <div class="form-group">
            <label for="name" class="control-label">Your Name:</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="Enter your name">
          </div>
          <div class="form-group">
            <label for="email" class="control-label">Email Address:</label>
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter your email">
          </div>
          <div class="form-group">
            <label for="message" class="control-label">Enter Your Message:</label>
            <textarea class="form-control" name="message" id="message" rows="3" placeholder="What's up?"></textarea>
          </div>
          <button type="submit"  name="submit" class="btn button btn-default">Submit</button>
        </form>

        <div id="success">
          <span>
            <p>Your message was sent succssfully! I will be in touch as soon as I can.</p>
          </span>
        </div>

        <div id="error">
          <span>
            <p>Something went wrong, try refreshing and submitting the form again.</p>
          </span>
        </div>

JS

 $(function(){
       $('form').validate({
             rules: {
                name:{
                required: true,
            minlength: 3
        },
        email: {
            required: true,
            email: true
        },
        message:{
            required: true,
            minlength: 10
        }
    },
    highlight: function (element, errorClass) {
        $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function (element, errorClass) {
        $(element).closest('.form-group').removeClass('has-error');
    },
   submitHandler: function(form) {
        var name = $('input#name').val();
        var email = $('input#email').val();
        var message = $('textarea#message').val();
        var dataString = ' name= ' + name + ' &email= ' + email + ' &message= ' + message;
        // alert(dataString);



        $(form).ajaxSubmit({
            type:"POST",
            data: $(form).serialize(),
            url:"process.php",
            success: function() {
                $('#contact :input').attr('disabled', 'disabled');
                $('#contact').fadeTo( "slow", 0.15, function() {
                    $(this).find(':input').attr('disabled', 'disabled');
                    $(this).find('label').css('cursor','default');
                    $('#success').fadeIn();
                });
            },
            error: function() {
                $('#contact').fadeTo( "slow", 0.15, function() {
                    $('#error').fadeIn();
                });
            }
        });


     }
});
});

PHP

<?php

$to = "youremail@domain.com";
$from = $_REQUEST['email'];
$name = $_REQUEST['name'];
$headers = "From: $from";
$subject = "You have a message.";

$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"phone"} = "phone";
$fields{"message"} = "message";

$body = "Here is what was sent:\n\n"; foreach($fields as $a => $b){   $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

$send = mail($to, $subject, $body, $headers);

?>
user3144418
  • 11
  • 1
  • 2

2 Answers2

3

You need to stop the default action of the submit by using either event.preventDefault(); or return false. Here is how to do the is with preventDefault():

submitHandler: function(form, event) { 
    event.preventDefault();
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
0
  1. Try giving the form an id, and try to do operations in js using that id.
  2. Never check user input using JS since it is changable on the client side. The perfect way to do it is to send it to a php file using ajax and validate user input on server side so that the client can't interfere with the validation process.
  3. Try to put alert('something something'); in various places of your code, during the runtime, the execution might not even come to where you submit the form. For example, start like this:

$(form).ajaxSubmit({ alert('something'); . . . });

If for example alert is not shown, it means that that part is not executed and you might want to try a different way.

  • 1
    [Quit using `alert()` for troubleshooting.](http://stravid.com/en/stop-the-javascript-alert-madness/), use `console.log()` instead. The OP's form has an id (`contact`). Validating on the client-side and server-side is what you should do. Client-side so you can guide the user, server-side to make sure the user didn't screw around. – Jay Blanchard Apr 01 '15 at 19:20
  • I tried this and the alert did not work. What does this mean? – user3144418 Apr 01 '15 at 19:53
  • As I said, that part of the code is not executed. Change this "$(form).ajaxSubmit" to this: "$('#contact').ajaxSubmit". And also you need to change this: "data: $(form).serialize()," to this: "data: $('#contact').serialize(),". See if alert works then. But as Blanchard suggested, alert is not the best way to debug. Use console if you know how to, if not, you can use alert. – Ömer Öksüzler Apr 01 '15 at 19:59
  • Never check user input using Javascript? Tell that to every major corporation with a website or online application in America. It's not a bad thing, it's just not the ONLY thing. So please, don't tell someone to stop doing something that's a basic requirement of every UI job out there. Front-end error checking is WAY more user-friendly and responsive than back-end checking. Yes, you have to check on the back-end, but that should be common sense. – bpeterson76 Apr 01 '15 at 20:57