简体   繁体   中英

Contact form not submitting using Ajax and PHP

I'm building a contact form for my site using jQuery validation plugin , ajax call to forward the data to the PHP file, and finally sending the email. Seems like the data is not passed to the php mailer . I'm new to server side technologies, I read a lot but still can't make this working, so please advise me.

the form:

<form class="form-horizontal" role="form" id="contactForm" name="contactForm" method="post">

<div class="form-group">
    <label class="col-lg-2 control-label" for="inputName">Name</label>
      <div class="col-lg-10">
          <input class="form-control" id="inputName" name="inputName" placeholder="Your name" type="text" value="" required>
     </div>
</div>

<div class="form-group">
   <label class="col-lg-2 control-label" for="inputEmail">Email</label>
   <div class="col-lg-10">
   <input class="form-control" id="inputEmail" name="email" placeholder="your@email.com" type="email" value="" required>   
   </div>
</div>

<div class="form-group">
   <label class="col-lg-2 control-label" for="inputMessage">Message</label>
   <div class="col-lg-10">
   <textarea class="form-control" id="inputMessage" name="inputMessage" placeholder="Message" rows="3"  required></textarea>
   <button class="btn btn-success pull-right" type="submit" name="submit" id="submit">Send</button>
   </div>
</div>

the javascript:

/*validate contact form */
$(function() {
    $('#contactForm').validate({
        rules: {
            inputName: {
                required: true,
                minlength: 2
            },
            inputEmail: {
                required: true,
                email: true
            },
            inputMessage: {
                required: true
            }
        },
        messages: {
            name: {
                required: "name required",
                minlength: "name must be at least 2 characters"
            },
            email: {
                required: "email required"
            },
            message: {
                required: "message required",
                minlength: 10
            }
        },
        submitHandler: function(form) {
            $('form').ajaxSubmit({

                type:"POST",
                data: $(form).serialize(),
                url:"index2.php",
                success: function() {

                    alert("message sent");
                },
                error: function() {
                    alert("due to an error msg wasnt sent");
                }
            });
        }
    });
});

php file:

<?php
if ($_POST["submit"]) {
    $name = trim($_POST['inputName']);
    $email = trim($_POST['inputEmail']);
    $message = $_POST['inputMessage'];
    $from = 'Demo Contact Form';
    $to = 'example@example.com';
    $subject = 'Message from Contact Demo ';

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    mail($to, $subject, $body, $from);
}
?>

$(form).serialize() doesn't include the submit field (how would it know which submit button you clicked on?), so if ($_POST['submit']) will never succeed. Use:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

instead.

Or, if this script is only used for AJAX calls, and not loaded directly by the browser, you can omit that check entirely, as in Glizzweb's answer.

In your ajax.php remove $_POST["submit"]

<?php
    $name = trim($_POST['inputName']);
    $email = trim($_POST['inputEmail']);
    $message = $_POST['inputMessage'];
    $from = 'Demo Contact Form';
    $to = 'example@example.com';
    $subject = 'Message from Contact Demo ';

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    mail($to, $subject, $body, $from);
?>

better use checking if:

  if (isset($_POST['inputName'])){
//rest part here
}

// and see if the file is in same directory otherwise give relative path.

use this to send form content:

submitHandler: function() {
    $('form').ajaxSubmit({

        type:"POST",
        data: $('#contactForm').serialize(),
        url:"submit.php",
        success: function() {

            alert("message sent");
        },
        error: function() {
            alert("due to an error msg wasnt sent");
        }
    });
}

In ajax page $_POST['submit'] need remove because you post values using "$(form).serialize()" and In you not post value to ajax page. remove if condition "if ($_POST["submit"]) {}" and change like this "if (!empty($_POST["inputName"])) { }"

 $name = trim($_POST['inputName']);
$email = trim($_POST['inputEmail']);
.....
....
....

Try this code:

<html>
<head>
<script src="js/jquery-1.11.0.js" type="text/javascript"></script>
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
<script src="js/additional-methods.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){

    $('#contactForm').submit(function(e){
        e.preventDefault();
    $('#contactForm').validate({
        rules: {
            inputName: {
                required: true,
                minlength: 2
            },
            inputEmail: {
                required: true,
                email: true
            },
            inputMessage: {
                required: true
            }
        },
        messages: {
            name: {
                required: "name value required",
                minlength: "name must be at least 2 characters"
            },
            email: {
                required: "email is required"
            },
            message: {
                required: "message is required",
                minlength: 10
            }
        },
        submitHandler: function(form) {
            alert($('form').html());
            $.ajax({

                type:"POST",
                data: $(form).serialize(),
                url:"test1.php",
                success: function() {

                    alert("message sent");
                },
                error: function() {
                    alert("due to an error msg wasnt sent");
                }
            });
        }
    });
});
});
</script>
</head>
<body>

    <form class="form-horizontal" role="form" id="contactForm" name="contactForm" method="post">

<div class="form-group">
    <label class="col-lg-2 control-label" for="inputName">Name</label>
      <div class="col-lg-10">
          <input class="form-control" id="inputName" name="inputName" placeholder="Your name" type="text" value="" >
     </div>
</div>

<div class="form-group">
   <label class="col-lg-2 control-label" for="inputEmail">Email</label>
   <div class="col-lg-10">
   <input class="form-control" id="inputEmail" name="email" placeholder="your@email.com" type="email" value="" >   
   </div>
</div>

<div class="form-group">
   <label class="col-lg-2 control-label" for="inputMessage">Message</label>
   <div class="col-lg-10">
   <textarea class="form-control" id="inputMessage" name="inputMessage" placeholder="Message" rows="3"  ></textarea>
   <input class="btn btn-success pull-right" type="submit" name="submit" id="submit" value="Send">
   </div>
</div>
</body>
</html>

It is working and showing message sent and ajax call also made. you are doing some mistakes while performing ajax call. as jquery validation plugin does not provide any ajaxsubmit function instead use jquery ajax function as i have used. try it and let me know for further issue.

Change this code to fit your requirement.

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