Bootstrap联系表格未发布

时间:2018-01-19 03:43:13

标签: javascript php html twitter-bootstrap express

我正在按照本教程创建表单:

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

在联系表单HTML的底部,我添加了脚本:

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

验证器文件来自我下载的Bootstrap。我知道它有效,因为它填写了我的表格。

当我提交表格时,没有任何反应。我在控制台中收到以下错误:

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

我把php文件放在php文件夹中,这样部分已经改变,但其他一切都是一样的。我已经尝试将php文件放在与联系页面相同的文件夹中并获得类似的消息:

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

我想知道是不是因为我正在使用node和express。我想在以下index.js文件中做一些事情?

这是我的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);
 });

以下是“联系”页面上的表单 - 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;
          }
       })
  });

1 个答案:

答案 0 :(得分:0)

我对节点不够深入,并表示要完全知道你的JavaScript是否可靠。我只能给出的建议是尝试在该教程中显示的JS,并将文件放在同一个位置。基本上重新创造一切。

之后,尝试将contact.php放在php文件夹中并修复操作。看看是否有效。

如果是这样,那么你就会知道这是你的JS。我知道Bootstrap依赖于JQuery,因此如果您已经将JQuery用于Bootstrap的其他功能,那么您可能需要考虑使用它们的脚本。如果没有,那么只需逐步进行大量的错误消息传递,直到找到问题所在。

抱歉,我无法提供更好的帮助。祝你好运!