简体   繁体   中英

Bootstrap Contact Form not posting

I'm following this tutorial to create a form:

https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form

At the bottom of the contact form HTML, I added the scripts:

  <script src='https://code.jquery.com/jquery-1.12.0.min.js'></script>
  <script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'>   </script>
  <script src='js/validator.js'></script>
  <script src='js/contact.js'></script>

The validator file is from Bootstrap, which I downloaded. I know it works because it validates my form as I fill it out.

When I submit the form, nothing happens. I get the following error in console:

  POST http://www.example.com/php/contact.php 404 (Not Found)

I put the php file in a php folder so that part has changed but everything else is the same. I've tried it by placing the php file in the same folder as the contact page and get a similar message:

  POST http://www.example.com/contact.php 404 (Not Found)

I'm wondering if it is because I am using node and express. I am I suppose to do something in the following index.js file?

This is my index.js:

  const express = require('express');
  const  app = express();
  const port = process.env.PORT || 3000;

  app.use(express.static('public'));
  app.set('view engine', 'ejs');

  app.get('/', function (request, response) {
      response.render('index');
  });

  app.get('/projects', function (request, response) {
      response.render('projects');
  });

  app.get('/about', function (request, response) {
      response.render('about');
  });

  app.get('/contact', function (request, response) {
      response.render('contact');
  });

  app.listen(port, function () {
       console.log('Listening on port ' + port);
 });

Here is the form on the Contact page - HTML:

<form id="contact-form" method="post" action="php/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">Firstname *</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">Lastname *</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 *</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</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"><strong>*</strong> These fields are required. Contact form template by <a href="http://bootstrapious.com" target="_blank">Bootstrapious</a>.</p>
          </div>
      </div>
  </div>
</form>

contact.php:

<?php
    $from = 'Demo contact form <demo@domain.com>';

    $sendTo = 'Demo contact form <demo@domain.com>';

    $subject = 'New message from contact form';

    $fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); 

    $okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';

    $errorMessage = 'There was an error while submitting the form. Please try again later';

    error_reporting(E_ALL & ~E_NOTICE);

    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 (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
      }

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

      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:

  $(function () {

  // downloaded validator files 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 receive 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;
          }
       })
  });

I'm not deep enough on node and express to fully know if your JavaScript is solid or not. Only advice I could give is to try the JS shown on that tutorial, and put the files in the same spot together. Basically recreate it all.

After that, try putting contact.php in the php folder and fix the action. See if that works.

If so, then you'll know it's your JS. I know Bootstrap is reliant on JQuery, so you might want to consider using their script if you are already using JQuery for other functions of Bootstrap. If not, then just go step by step with plenty of error messaging until you find where you hit an issue.

Sorry I can't be of better help. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM