skip to Main Content

I have currently been following a tutorial and so far the contact form works perfect as it should. The only problem I have is when the user clicks submit it takes them to another page saying thank you and not a bootstrap pop up on the same page saying thank you as it should. The form otherwise functions perfectly. Thanks for any help!

contact.php

<?php
/*
 *  CONFIGURE EVERYTHING HERE
 */

// an email address that will be in the From field of the email.
$from = 'Demo contact form <[email protected]>';

// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <[email protected]>';

// 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 formn=============================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]: $valuen";
        }
    }

    // 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

Answers


  1. Just prevent the form from submitting itself

    $('#contact-form').on('submit', function (e) {
        e.preventDefault();
    
        // REMOVE THIS STATEMENT if (!e.isDefaultPrevented()) {
           var url = "contact.php";
    ...
    
    Login or Signup to reply.
  2. Problem 1:

    There is something wrong with the second jQuery library.

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

    When I click the submit button, the following error message is raised:

    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
    

    Though there is nothing wrong with the ajax request code. So, either use

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

    or this:

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

    In any case, don’t use two libraries at the same time.


    Problem 2

    In your presented contact.js page, the first character is C, before $(function () {. Just remove it from your real code if you have it in there too.


    EDIT 1:

    I just tested it and it works ok. E.g. the bootstrap’s message alert is displayed. So:

    • I commented the mail() function in contact.php. So, please test yourself with mail() commented.
    • The https://.../bootstrap.min.js script doesn’t accept any integrity attribute. The same applies for the https://.../bootstrap.min.css link tag. Please resolve these problems too, reedit your question, and give a feedback.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search