php jQuery表单工作直到我添加了ajax

时间:2016-06-23 19:32:55

标签: php jquery ajax

我试图通过一些jQuery验证和使用ajax的php验证使这个表单尽可能简单。一切都工作正常,直到我试图包括ajax。

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

    <script type="text/javascript">                                 
// we will add our javascript code here
jQuery(document).ready(function($) {

    $("#ajax-contact-form").submit(function() {
        var str = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "contactfinal.php",
            data: str,
            success: function(msg) {
                if(msg == 'OK') {
                    result = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>';
                    $("#fields").hide();
                } else {
                    result = '<div class="alert alert-danger" role="alert"><p><strong>There were error(s) in your form:</strong></p>' + error + '</div>';
                }

            }
        });
        return false;
    });
});
</script>  
  </head>
  <body>

      <div class="container">

    <h1>Get in touch!</h1>

      <div id="error"><? echo $error.$successMessage; ?></div>

     <form id="ajax-contact-form" action="">
  <fieldset class="form-group">
    <label for="email">Email address</label>
    <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
    <small class="text-muted">We'll never share your email with anyone else.</small>
  </fieldset>
  <fieldset class="form-group">
    <label for="subject">Subject</label>
    <input type="text" class="form-control" id="subject" name="subject" >
  </fieldset>
  <fieldset class="form-group">
    <label for="exampleTextarea">What would you like to ask us?</label>
    <textarea class="form-control" id="content" name="content" rows="3"></textarea>
  </fieldset>
  <button type="submit" id="submit" class="btn btn-primary">Submit</button>
</form>

        </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>




  </body>
</html>

contactfinal.php

<?php

    $error = ""; $successMessage = "";

    if ($_POST) {

        if (!$_POST["email"]) {

            $error .= "An email address is required.<br>";

        }

        if (!$_POST["content"]) {

            $error .= "The content field is required.<br>";

        }

        if (!$_POST["subject"]) {

            $error .= "The subject is required.<br>";

        }

        if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {

            $error .= "The email address is invalid.<br>";

        }

        if ($error != "") {

            $error = '<div class="alert alert-danger" role="alert"><p>There were error(s) in your form:</p>' . $error . '</div>';

        } else {

            $emailTo = "me@mydomain.com";

            $subject = $_POST['subject'];

            $content = $_POST['content'];

            $headers = "From: ".$_POST['email'];

            if (mail($emailTo, $subject, $content, $headers)) {

                $successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>';


            } else {

                $error = '<div class="alert alert-danger" role="alert"><p><strong>Your message couldn\'t be sent - please try again later</div>';


            }

        }



    }

?>

2 个答案:

答案 0 :(得分:1)

问题是你在加载jQuery库之前尝试执行jQuery脚本。尝试在加载bootstrap.min.js文件后立即移动整个jQuery echo $successMessage代码段,一切都会正常工作。

不确定您是否在那里,但PHP部分不会返回任何响应。如果您希望能够从AJAX响应中附加错误/成功消息,则应使用echo $errorecho

你应该json_encode回复,或者更高级,你可以<?php $error = ""; $successMessage = ""; if ($_POST) { if (!$_POST["email"]) { $error .= "An email address is required.<br>"; } if (!$_POST["content"]) { $error .= "The content field is required.<br>"; } if (!$_POST["subject"]) { $error .= "The subject is required.<br>"; } if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) { $error .= "The email address is invalid.<br>"; } if ($error != "") { $error = '<div class="alert alert-danger" role="alert"><p>There were error(s) in your form:</p>' . $error . '</div>'; echo $error; } else { $emailTo = "me@mydomain.com"; $subject = $_POST['subject']; $content = $_POST['content']; $headers = "From: ".$_POST['email']; if (mail($emailTo, $subject, $content, $headers)) { $successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>'; echo $successMessage; } else { $error = '<div class="alert alert-danger" role="alert"><p><strong>Your message couldn\'t be sent - please try again later</div>'; echo $error; } } } ?> 在数组中 -

<script type="text/javascript">                                 
// we will add our javascript code here
jQuery(document).ready(function($) {

    $("#ajax-contact-form").submit(function() {
        var str = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "contactfinal.php",
            data: str,
            success: function(response) {

                $('#error').html(response);

            }
        });
        return false;
    });
});
</script> 

接下来,由于服务器正在返回消息,您只需将响应附加到错误持有者

<div id="error"><? echo $error.$successMessage; ?></div>

此部分javascript无效,因为您尝试将<div id="error"></div>字符串打印到PHP中。如果您正在关注上面的AJAX代码段,则只需使用空div {{1}}替换该部分

答案 1 :(得分:0)

在document.ready function

之前移动此脚本
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>