Ajax代码在首次运行时无法正常工作

时间:2018-03-20 16:53:59

标签: php jquery ajax

我在PHP页面上有一个Ajax脚本,用于在单击按钮时运行php脚本。

代码如下:

    <script>
$('#signup-form').submit(function(e){
    e.preventDefault(); // Prevent Default Submission
    $.ajax({
    url: 'insertfromsession.php',
    type: 'POST',
    data: $(this).serialize(), // it will serialize the form data
        dataType: 'html'
    })
    .done(function(data){
        $('#form-container').fadeOut('slow', function(){
             $('#form-container').fadeIn('slow').html(data);
        });

        document.getElementById('submitBtn').disabled = true;
        document.getElementById("submitBtn").value="Thanks!";
    })
    .fail(function(){
        alert('Ajax Submit Failed ...');
    });
});

当我第一次打开网页时,脚本没有运行,但如果我再次单击并重复该过程,则脚本会执行而不会出现问题。有谁知道造成这个问题的原因是什么?

运行此代码的Insert.php在这里:

    <!DOCTYPE html>
    <html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="js/submit.js"></script>
        <!-- /.website title -->
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

        <!-- CSS Files -->
        <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="css/font-awesome.min.css" rel="stylesheet">
        <link href="fonts/icon-7-stroke/css/pe-icon-7-stroke.css" rel="stylesheet">
        <link href="css/animate.css" rel="stylesheet" media="screen">
        <link href="css/owl.theme.css" rel="stylesheet">
        <link href="css/owl.carousel.css" rel="stylesheet">
        <style type="text/css">
           body { background: white !important; } /* Adding !important forces the browser to overwrite the default style applied by Bootstrap */
        </style>
        <!-- Colors -->
        <link href="css/css-index.css" rel="stylesheet" media="screen">
        <!-- <link href="css/css-index-green.css" rel="stylesheet" media="screen"> -->
        <!-- <link href="css/css-index-purple.css" rel="stylesheet" media="screen"> -->
        <!-- <link href="css/css-index-red.css" rel="stylesheet" media="screen"> -->
        <!-- <link href="css/css-index-orange.css" rel="stylesheet" media="screen"> -->
        <!-- <link href="css/css-index-yellow.css" rel="stylesheet" media="screen"> -->

        <!-- Google Fonts -->
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic" />
    </head>

        <div id="top"></div>
        <div class="fullscreen landing parallax" style="background-image:url('images/fireworks.jpg');" data-img-width="2000" data-img-height="1333" data-diff="100">
            <div class="overlay">
                <div class="container">
                    <div class="row">
                        <div class="col-md-10">
                            <!-- /.logo -->
                            <!-- /.main title -->
                            <h2 class="wow fadeInLeft">Thank you for submitting your details</h2>
                            <h2 class="wow bounce infinite">While you are here, why not apply for one of other fantastic products?</h2>


                                <?php
                                session_start();

                                include ("dbconnect.php");

                                // prepare and bind
                                $stmt = $conn->prepare("INSERT INTO wills (forename,surname,postcode,telno,email,ipaddress,capturedate,url,user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                                $stmt->bind_param("sssssssss", $forename, $surname, $postcode, $telno, $email, $ipaddress, $capturedate, $url, $user);

                                $forename         = $_POST["forename"];
                                $surname          = $_POST["surname"];
                                $postcode         = $_POST["postcode"];
                                $telno            = $_POST["telno"];
                                $email            = $_POST["email"];
                                $ipaddress        = $_SERVER['REMOTE_ADDR'];
                                $capturedate      = date('Y-m-d H:i:s');
                                $url              ="www.test.com";
                                $user             ="testuser";

                                $_SESSION["forename"] = $forename;
                                $_SESSION["surname"] = $surname;
                                $_SESSION["postcode"] = $postcode;
                                $_SESSION["telno"] = $telno;
                                $_SESSION["email"] = $email;
                                $_SESSION["ipaddress"] = $ipaddress;
                                $_SESSION["capturedate"] = $capturedate;
                                $_SESSION["url"] = $url;
                                $_SESSION["user"] = $user;

                                echo "<br>"."Forename: ".$forename."<br>";
                                echo "Surname: ".$surname."<br>";
                                echo "Telno: ".$telno."<br>";
                                echo "Email: ".$email."<br>";
                                echo "IP Address: ".$ipaddress."<br>";
                                echo "Session User: ".$_SESSION["user"]."<br>";

                                if (!$stmt->execute()) {
                                    echo $stmt->error;
                                } else {

                                }

                                $stmt->close();
                                $conn->close();
                                ?>

                            </div>
                        </div>




                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="text-center"><a href="index.html">Back to Main Page</a></div>

                            <div class="col-md-12">

                                <!-- /.product 1 -->
                                <div class="col-sm-6 feat-list">
                                    <i class="pe-7s-phone pe-5x pe-va wow fadeInUp"></i>
                                    <div class="inner">
                                        <h4>Grab a Mobile SIM</h4>
                                           <p>With a SIM only contract, you get the all the benefits of an ongoing contract, without the additional high cost of a handset.
                                           Short-term SIM only contracts give you freedom and flexibility. All the networks offer them from as little as 30 days, and you can then keep them rolling month-by-month
                                        </p>
                                            <form method="post" id="signup-form" autocomplete="off">
                                                <div class="form-group">
                                                    <input type="submit" class="btn btn-success btn-block btn-lg" id="submitBtn" value="Apply for Mobile Sim?">
                                                </div>
                                            </form>
                                    </div>


                                </div>
                                   <!-- /.product 2 -->
                                    <div class="col-sm-6 feat-list">
                                        <i class="pe-7s-like2 pe-5x pe-va wow fadeInUp"></i>
                                        <div class="inner">
                                        <h4>Debt Plan</h4>
                                            <p>Do you have more than &pound5,000 worth of debt?<br>
                                            Do you need help to reduce the monthly payments?<br>
                                            If so, find out if you qualify to write off up to 80% of your debt here</p>
                                        <form method="post" id="signup-formdebt" autocomplete="off">
                                        <div class="form-group">
                                            <input type="submit" class="btn btn-success btn-block btn-lg" id="submitBtndebt" value="Get help now">
                                        </div>
                                        </form>
                                    </div>
                                </div>


                            </div>

        <!-- /.footer -->
        <footer id="footer">
            <div class="container">
                <div class="col-sm-4 col-sm-offset-4">
                    <!-- /.social links -->
                    <div class="social text-center">
                        <ul>
                            <li><a class="wow fadeInUp" href="https://twitter.com/"><i class="fa fa-twitter"></i></a></li>
                            <li><a class="wow fadeInUp" href="https://www.facebook.com/" data-wow-delay="0.2s"><i class="fa fa-facebook"></i></a></li>
                        </ul>
                    </div>
                    <a href="#" class="scrollToTop"><i class="pe-7s-up-arrow pe-va"></i></a>
                </div>
            </div>
        </footer>

        <!-- /.javascript files -->
        <script src="js/jquery.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <script src="js/custom.js"></script>
        <script src="js/jquery.sticky.js"></script>
        <script src="js/wow.min.js"></script>
        <script src="js/owl.carousel.min.js"></script>
        <script>
                                    new WOW().init();
        </script>
    </body>
    <script>
$( document ).ready(function() {
    $('#signup-form').submit(function(e){
        e.preventDefault(); // Prevent Default Submission
        $.ajax({
        url: 'insertfromsession.php',
        type: 'POST',
        data: $(this).serialize(), // it will serialize the form data
            dataType: 'html'
        })
        .done(function(data){
            $('#form-container').fadeOut('slow', function(){
                 $('#form-container').fadeIn('slow').html(data);
            });

            document.getElementById('submitBtn').disabled = true;
            document.getElementById("submitBtn").value="Thanks!";
        })
        .fail(function(){
            alert('Ajax Submit Failed ...');
        });
    });
});
    </script>

        <script>

        $( document ).ready(function() {
            console.log( "ready!" );
                    $('#signup-formdebt').submit(function(e){
                        e.preventDefault(); // Prevent Default Submission
                        $.ajax({
                        url: 'insertfromsessiondebt.php',
                        type: 'POST',
                        data: $(this).serialize(), // it will serialize the form data
                            dataType: 'html'
                        })
                        .done(function(data){
                            $('#form-container').fadeOut('slow', function(){
                                 $('#form-container').fadeIn('slow').html(data);
                            });

                            document.getElementById('submitBtndebt').disabled = true;
                            document.getElementById("submitBtndebt").value="Thanks!";
                        })
                        .fail(function(){
                            alert('Ajax Submit Failed ...');
                        });
                    });

        });

    </script>

</html>

2 个答案:

答案 0 :(得分:0)

我认为我解决了这个问题,它与AJAX没什么关系。它实际上似乎是会话变量的问题。我将insert.php上的会话变量移到了前面的顶部,这使它按预期工作。

感谢您的努力人员

答案 1 :(得分:-1)

您应该使用document.ready功能。以下是jQuery版本文档的链接:https://learn.jquery.com/using-jquery-core/document-ready/