联系表单无需刷新

时间:2014-10-28 15:01:31

标签: php jquery contact-form

我一直试图创建此表单以显示错误或没有页面刷新的确认消息。

我一直在尝试使用jQuery,但没有成功。我的jQuery代码是完全错误的,我现在尝试创建它太多次了。

有人可以指出我正确的方向吗?

HTML

   <form method="post" action="index.php" autocomplete="on">

        <label>Name</label>
        <input name="name" placeholder="What is your name?">

        <label>Email</label>
        <input name="email" type="email" placeholder="Your email please">

        <label>Message</label>
        <textarea rows="10"name="message" placeholder="What would you like to say?"></textarea>

        <label>*What is 2+2? (Anti-spam)</label>
        <input name="human" placeholder="Type Here">

        <input id="submit" name="submit" type="submit" value="Submit">

    </form>

PHP

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: removed '; 
    $to = 'removed'; 
    $subject = 'From: removed';
    $human = $_POST['human'];

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

    if ($_POST['submit']) {
        if ($name != '' && $email != '') {
            if ($human == '4') {                 
                if (mail ($to, $subject, $body, $from)) { 
                echo '<p>Your message has been sent!</p>';
            } else { 
                echo '<p>Something went wrong, go back and try again!</p>'; 
            } 
        } else if ($_POST['submit'] && $human != '4') {
            echo '<p>You answered the anti-spam question incorrectly!</p>';
        }
        } else {
            echo '<p>You need to fill in all required fields!!</p>';
        }
    }
?>

2 个答案:

答案 0 :(得分:2)

从jQuery看一下$ .post。

你可以有一个这样的表格:

<form id="form">
    <label for="field">Field</label><br />
    <input name="field" id="field" placeholder="Field" />
    <span id="responseField"></span>
    <br /><br />
    <input type='submit' value='Send !'/>
</form>

这样的PHP检查:

$json = array("status" => "OK", "error" => []);
if (isset($_POST['field'])) // Test if every field is here
{
    // Test if "field" is OK
    if (!preg_match("/^[a-zA-Z0-9]+$/", $_POST['field']))
    {
        $json['status'] = "NO";
        $json['error']['field'] = "Must be alphanumeric";
    }
}
else
    $json['status'] = "NO";

echo json_encode($json);
exit();

和那样的JS

$(document).on("ready", function() {
    $("#form").submit(function() {
        var url = "check.php";
        $.post(url, {field: $("#field").val()}, function(data) {
            var json = $.parseJSON(data);
            if (json.status == "OK")
                alert("Everything is OK!");
            else
                $("#responseField").html(json.error.field || "");
        });
        return false;
    });
});

会发生什么:您发送“字段”值,在PHP中检查(此处,只是一个字母数字检查,执行您想要的操作)。在检查表单时,请填写$json变量。之后发送。然后,您的JS将检查一切是否正常,否则它将在该字段后的范围内打印您的反馈。

为了获得更多的可移植性,请检查JasonK的答案,它会自动发送整个表单,这比构建要发送的对象更好。他还检查ajax请求是否失败,这是一个非常好的习惯,我的代码是最简单的理解AJAX请求是如何工作的。

答案 1 :(得分:1)

是的,我可以。为了实现这一目标,您需要使用AJAX。类似下面的东西应该可以工作,但我还没有测试过:

$('form').submit(function(e) {
    var formData = $(this).serialize(); //Get the form data (input)

    //Post with AJAX
    $.post("post-contact.php", formData)
    .done(function(data) {
        alert('Succes!')
    })
    .fail(function(data) {
        alert('Failed!')
    }); 

    return false; //Prevent form from being submitted (same as e.preventDefault())
});

我希望这可以帮到你,你应该阅读文档以获取更多信息。