联系表单未正确使用ajax

时间:2016-03-27 18:59:05

标签: php jquery ajax

我有一个正常的php联系表单示例,我根据自己的需要进行了修改。然后我想用ajax发布到我的php邮件脚本。出于某种原因,我仍然会在我的网址中看到这样的帖子值:

http://www.example.com?name=bruno&email=bruno%40gmail.com&subject=ajax+test+ff&message=test

我也无法从我的php获得关于发送是否成功的正确回复。如果成功,我想显示一条消息。

然后发送电子邮件。

这是我的代码:

HTML

<form>
    <input type="text" class="form-control" id="name" name="name" placeholder="Name">
    <input type="email" id="email" name="email" class="form-control" placeholder="Email">
    <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject">
    <textarea class="form-control" id="message" name="message" placeholder="Message" rows="4"></textarea>
    <button id="submit" class="form-control text-uppercase">Send</button>
</form>

的jQuery

$( document ).ready(function() {
    $("#submit").click(function(){
         var data = {
         name:$("#name").val(),
         email:$("#email").val(),
         subject:$("#subject").val(),
         message:$("#message").val(),
      }
            $.ajax({
                type: "POST",
                url: "sendmail.php",
                data: data,
                dataType: 'json',
                cache: false,
            })
            .success(function(response) {
                if(!response.errors && response.result=="success") {
                alert("success")
                } else 
                if(!response.errors && response.result=="oops") {
                alert("oops somethign went wrong");
                }
            });
    });
});

PHP

<?php
    $inputvalues = $_POST;
    $errors = false;
    $result = false;

    $email_to = "bruno@example.com";
    $email_from = "info@example.com";
    $name = $inputvalues["name"];
    $email = $inputvalues["email"];
    $message = $inputvalues["message"];
    $email_subject = $inputvalues["subject"];
    $headers = "From: " . $email_from . "\n";
    $headers .= "Reply-To: " . $email . "\n";
    $message = "Name: ". $name . "\r\nMessage: " . $message;
    ini_set("sendmail_from", $email_from);
    $sent = mail($email_to, $email_subject, $message, $headers, "-f" .$email);
    if ($sent) {
       $returnResult = "success";
    } 
    else {
        $returnResult = "oops";
    }
       echo json_encode(['result' => $returnResult, 'errors' => $errors]);
?>

1 个答案:

答案 0 :(得分:0)

您需要阻止在您的听众中提交表单,即

$( document ).ready(function() {
    $("#submit").click(function(event){
         event.preventDefault();
         var data = {
         // etc.