联系表格无法重置

时间:2018-04-10 06:31:40

标签: javascript php ajax html5

我希望在我的网站上创建一个联系我们表单,在提交表单后,应该清除文本字段,并且应该出现感谢信。

这是html代码:

<div class="form">
<div id="sendmessage">Your message has been sent. Thank you!</div>

<form action="contactform.php" method="post" role="form" class="contactForm">
    <div class="form-group">
        <input type="text" name="name" class="form-control" id="name" placeholder="Name (eg: James)" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
        <div class="validation"></div>
    </div>
    <div class="form-group">
        <input type="email" class="form-control" name="email" id="email" placeholder="Email (eg: james@example.com)" data-rule="email" data-msg="Please enter a valid email" />
        <div class="validation"></div>
    </div>
    <div class="form-group">
        <input type="text" class="form-control" name="subject" id="subject" placeholder="Phone Number (eg: 0406 624 456)" data-rule="minlen:9" data-msg="Please enter a valid contact number" />
        <div class="validation"></div>
    </div>
    <div class="form-group">
        <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
        <div class="validation"></div>
    </div>
    <br/>
    <div class="text-center">
        <button type="submit" name="submit" value="Submit"></button>
        <!--b>Send Message</b-->
    </div>
</form>

相关的java脚本代码:

 jQuery(document).ready(function($) {
  "use strict";

//Contact
$('form.contactForm').submit(function(){
    var f = $(this).find('.form-group'), 
    ferror = false, 
    emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

    f.children('input').each(function(){ // run all inputs

        var i = $(this); // current input
        var rule = i.attr('data-rule');

        if( rule !== undefined ){
        var ierror=false; // error flag for current input
        var pos = rule.indexOf( ':', 0 );
        if( pos >= 0 ){
            var exp = rule.substr( pos+1, rule.length );
            rule = rule.substr(0, pos);
        }else{
            rule = rule.substr( pos+1, rule.length );
        }

        switch( rule ){
            case 'required':
            if( i.val()==='' ){ ferror=ierror=true; }
            break;

            case 'minlen':
            if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
            break;

            case 'email':
            if( !emailExp.test(i.val()) ){ ferror=ierror=true; }
            break;

            case 'checked':
            if( !i.attr('checked') ){ ferror=ierror=true; }
            break;

            case 'regexp':
            exp = new RegExp(exp);
            if( !exp.test(i.val()) ){ ferror=ierror=true; }
            break;
        }
            i.next('.validation').html( ( ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
        }
    });
    f.children('textarea').each(function(){ // run all inputs

        var i = $(this); // current input
        var rule = i.attr('data-rule');

        if( rule !== undefined ){
        var ierror=false; // error flag for current input
        var pos = rule.indexOf( ':', 0 );
        if( pos >= 0 ){
            var exp = rule.substr( pos+1, rule.length );
            rule = rule.substr(0, pos);
        }else{
            rule = rule.substr( pos+1, rule.length );
        }

        switch( rule ){
            case 'required':
            if( i.val()==='' ){ ferror=ierror=true; }
            break;

            case 'minlen':
            if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
            break;
        }
            i.next('.validation').html( ( ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
        }
    });
    if( ferror ) return false; 
    else var str = $(this).serialize();     
        $.ajax({
            // alert("enterd the loop")
            type: "POST",
            url: "contactform/contactform.php",
            data: str,
            success: function(msg){
               //alert(msg);
                if(msg == "New record created successfully") {
                    $("#sendmessage").addClass("show");         
                    $("#errormessage").removeClass("show"); 
                    $('.contactForm').find("input, textarea").val("");
                    document.getElementsByClassName("contactForm").reset();
                }
                else {
                    $("#sendmessage").removeClass("show");
                    $("#errormessage").addClass("show");
                    $('#errormessage').html(msg);
                }

            }
        });
    return false;
    });

 });

获取数据库凭据和属性的相关php脚本:

    <?php include "../../inc/dbinfo.inc"; ?>

<?php

$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);

  if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();

  $database = mysqli_select_db($connection, DB_DATABASE);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$Phone = test_input($_POST["Phone"]);
$message = test_input($_POST["message"]);
$submit = test_input($_POST["Submit"])
}


function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}


$sql = "INSERT INTO contact_details (name, email, Phone, message)
VALUES ('$name', '$email', '$Phone', '$message')";

// <script>alert("your message is sent successfully");
//  window.location="index.html";
// </script>

if ($connection->query($sql) === TRUE) {

echo "New record created successfully";
mysqli_free_result($result);
mysqli_close($connection);
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
mysqli_free_result($result);
mysqli_close($connection);
}

?>

提交表单后,表单不会重置并显示任何消息,但会在数据库中更新。

1 个答案:

答案 0 :(得分:0)

重定向到新页面或同一页面如下:

if ($connection->query($sql) === TRUE) {
    mysqli_free_result($result);
    mysqli_close($connection);
    header('Location: filename?msg=success');
}