PHP联系表单未登陆右页

时间:2018-03-13 17:50:45

标签: php jquery forms

我目前一直在关注一个教程,到目前为止,联系表单应该是完美的。我遇到的唯一问题是,当用户点击提交时,它会将他们带到另一个页面说谢谢,而不是在同一页面上弹出一个引导程序,说谢谢你应该这样做。否则表格完美无缺。谢谢你的帮助!

contact.php

<?php
/*
 *  CONFIGURE EVERYTHING HERE
 */

// an email address that will be in the From field of the email.
$from = 'Demo contact form <demo@domain.com>';

// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <demo@domain.com>';

// subject of the email
$subject = 'New message from contact form';

// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); 

// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';

// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';

/*
 *  LET'S DO THE SENDING
 */

// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(0);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');

    $emailText = "You have a new message from your contact form\n=============================\n";

    foreach ($_POST as $key => $value) {
        // If the field exists in the $fields array, include it in the email 
        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

    // All the neccessary headers for the email.
    $headers = array('Content-Type: text/plain; charset="UTF-8";',
        'From: ' . $from,
        'Reply-To: ' . $from,
        'Return-Path: ' . $from,
    );

    // Send email
    mail($sendTo, $subject, $emailText, implode("\n", $headers));

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}


// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
// else just display the message
else {
    echo $responseArray['message'];
}

contact.js

C$(function () {

    // init the validator
    // validator files are included in the download package
    // otherwise download from http://1000hz.github.io/bootstrap-validator

    $('#contact-form').validator();


    // when the form is submitted
    $('#contact-form').on('submit', function (e) {

        // if the validator does not prevent form submit
        if (!e.isDefaultPrevented()) {
            var url = "contact.php";

            // POST values in the background the the script URL
            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    // data = JSON object that contact.php returns

                    // we recieve the type of the message: success x danger and apply it to the 
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    // let's compose Bootstrap alert box HTML
                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';

                    // If we have messageAlert and messageText
                    if (messageAlert && messageText) {
                        // inject the alert to .messages div in our form
                        $('#contact-form').find('.messages').html(alertBox);
                        // empty the form
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
});

contact.html

      <!DOCTYPE html>
<html>

<head>
    <title>The Beckwood - Scunthorpe</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

        <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Satisfy" rel="stylesheet">
            <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">


</head>

<body>
<div id="wrap">
    <div class="header-main">

        <nav class="navbar navbar-default">
            <div class="container">
                <a class="navbar-brand" href="index.html" >
                     <img src="assets/img/logo.png">

                </a>
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                </div>
                <div class="collapse navbar-collapse" id="myNavbar">
                    <ul class="nav navbar-nav navbar-right">
                        <li><a href="index.html">HOME</a></li>
                         <li><a href="menu.html">MENU</a></li>
                          <li><a href="gallery.html">GALLERY</a></li>
                           <li><a href="about.html">ABOUT</a></li>
                            <li><a href="book.html">BOOK A TABLE</a></li>
                            <li><a href="contact.html">CONTACT</a></li>
                        </ul>

                    </div>
            </div>
        </nav>
        <div class="hero">
            <h1 id="welcome">Contact The Beckwood</h1>
            <p>Please use the below form to contact us. We will try our best to get back to you as soon as possible!</p>
            <div class="btn btn-primary"><a href="menu.html">View Menu</a></div>
            <div class="btn btn-primary"><a href="menu.html">Book a table</a></div>
        </div>
    </div>



</div>

<div class="container">
    <div class="intro">
        <h1> Contact Us </h1>
        <p>Welcome to the Beckwood! Here at the beckwood we specialise in authentic home made dishes hand cooked by our chefs.<br> Not only do we offer beautiful food we also provide entertainment, live sports and great quality beer.<br> Not only do we offer beautiful food we also provide entertainment.</p>
    </div>
</div>

        <div class="container">

            <div class="row">

                <div class="col-lg-8 col-lg-offset-2">

                   <br><br>

                    <form id="contact-form" method="post" action="contact.php" role="form">

                        <div class="messages"></div>

                        <div class="controls">

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="form_name">First Name *</label>
                                        <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="form_lastname">Surname *</label>
                                        <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="form_email">Email Address *</label>
                                        <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="form_phone">Phone Number</label>
                                        <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="form_message">Message *</label>
                                        <textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <input type="submit" class="btn btn-success btn-send" value="Send message">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <p class="text-muted"><br><strong>*</strong> Please complete all fields.</p>
                                </div>
                            </div>
                        </div>

                    </form>

                </div><!-- /.8 -->

            </div> <!-- /.row-->

        </div> <!-- /.container-->

<br><br>

<footer id="myFooter">
        <div class="container">
            <div class="row">
                <div class="col-sm-3">
                    <img id="footerlogo" src="assets/img/logo.png">
                </div>
                <div class="col-sm-4">
                    <h5>Thank you</h5>

                        <p>We would like to thank you for taking the time and visiting thebeckwood.co.uk. If you have any queries please don't hesitate to use the contact us button or give us a quick phone call.</p>

                </div>
                <div class="col-sm-1">
                    <h5>Navigation</h5>
                    <ul>
                        <li><a href="index.html">Home</a></li>
                        <li><a href="menu.html">Menu</a></li>
                        <li><a href="gallery.html">Gallery</a></li>
                        <li><a href="about.html">About</a></li>
                        <li><a href="book.html">Book</a></li>
                        <li><a href="contact.html">Contact</a></li>
                    </ul>
                </div>

                <div class="col-sm-4">
                    <div class="social-networks">
                        <a href="#" class="twitter"><i class="fa fa-twitter"></i></a>
                        <a href="#" class="facebook"><i class="fa fa-facebook"></i></a>
                        <a href="#" class="google"><i class="fa fa-google-plus"></i></a>
                        <a href="#" class="google"><i class="fa fa-instagram"></i></a>
                    </div>
                    <button type="button" class="btn btn-default"> <a href="contact.html"> Contact us </a></button>
                </div>
            </div>
        </div>
        <div class="footer-copyright">
            <p>© 2018 The Beckwood.</p>
        </div>
    </footer>



<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<script src="validator.js"></script>
<script src="contact.js"></script>

</body>

</html>

2 个答案:

答案 0 :(得分:1)

问题1:

第二个 jQuery 库存在问题。

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>

单击“提交”按钮时,将引发以下错误消息:

TypeError: $.ajax is not a function[Learn More]     contact.js:18:13
    <anonymous> http://[...my-path...]/contact.js:18:13
    dispatch https://code.jquery.com/jquery-3.2.1.slim.min.js:3:10499
    add/q.handle https://code.jquery.com/jquery-3.2.1.slim.min.js:3:8561

虽然 ajax 请求代码没有任何问题。所以,要么使用

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

或者这个:

<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

在任何情况下,请勿同时使用两个库。

问题2

在您提交的contact.js页面中,第一个字符为C,位于$(function () {之前。如果您已将其从实际代码中删除,请将其删除。

编辑1:

我刚刚测试过,它运行正常。例如。显示引导程序的消息警告。所以:

  • 我评论了 contact.php 中的mail()函数。因此,请使用mail()评论来测试自己。
  • https://.../bootstrap.min.js脚本不接受任何integrity属性。这同样适用于https://.../bootstrap.min.css 链接标记。请解决这些问题,重新提出问题并提供反馈。

答案 1 :(得分:0)

只是阻止表单提交

  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   // overridePendingTransition(R.anim.fadein, R.anim.fadeout);
    setContentView(R.layout.activity_intro);

    ImageView image = (ImageView) findViewById(R.id.myImageView);
    image.setImageResource(R.drawable.landscape);

    // go to the intro activity when button is pressed
    Button introBtn = (Button) findViewById(R.id.introBtn);
    introBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            startActivity(new Intent(MainActivity.this, IntroActivity.class));
        }});

    // when back btn is pressed the previous image shows up
    Button backBtn = (Button) findViewById(R.id.previousBtn);
    backBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
              backImage();
            ImageView image1 = (ImageView) findViewById(R.id.myImageView);
            image1.setImageResource(allDrawableImages.get(count));
        }

    });

    // a btn to set wallpaper
    Button setWallBtn = (Button)findViewById(R.id.setWallpaper);
    setWallBtn.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            WallpaperManager myWallpaperManager
                    = WallpaperManager.getInstance(getApplicationContext());
            try {
                myWallpaperManager.setResource(allRawImages.get(count));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }});

    // go to the next wallpaper image
    Button nextBtn = (Button) findViewById(R.id.nextBtn);
    nextBtn.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View arg0){
               nextImage();
            ImageView image2 = (ImageView) findViewById(R.id.myImageView);
            image2.setImageResource(allDrawableImages.get(count));
            }
        });
        }