donglei2288 2015-09-23 16:33
浏览 443

在bootstrap模式窗口中提交表单后显示错误或成功消息

I have a form in a bootstrap modal window, whereby the form is being processed through php,- this part does work fine in fact. However, I would like to either show a success or fail message to the user either right within the modal window or at least on the same page as the user originally was (right now the messages are stated on a blank page created by my php file). I pretty much used the same mechanics (i.e. php ajax combination) before, the only difference being that I've never used this code within a modal window. Somehow I just don't get it to work. Any help is much appreciated:)

Here is the relevant part of my html code:

<div class="container">
  <div class="row text-center orderprocess">
    <div class="col-sm-4 col-md-4 col-lg-4">
      <div class="frame_orderprocess">
        <h1>1</h1>
        <h2>Dr&aumlksak bestellen</h2>
        <p>Bestellen Sie online oder nehmen Sie telefonisch Kontakt auf.</p>
        <img src="img/Produkte/Draeksak/iconmonstr-email-4-icon-128.png" class="img-responsive center-block"/>
      </div><!--frame orderprocess-->
      <div class="highlight"><a href="#myModal" role="button" data-toggle="modal" class="linktext">--> Jetzt bestellen</a></div>
      <div id="form-messages" style="margin-top:1em; font-size:1.4em;"></div>
    </div><!--/col-4-->


    <!-- Modal -->
    <div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3 class="modal-title">Dr&aumlksak bestellen</h3>
          </div>
          <div class="modal-body">
            <form role="form" id="ajax" method="post" action="php/dsshop.php">
              <div class="container-fluid">
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <input type="text" class="form-control" id="firma" name="firma" required placeholder="Firma (falls vorhanden)">
                      <span class="help-block" style="display: none;">Bitte geben Sie Ihren Firmennamen ein (falls vorhanden).</span>
                    </div>
                  </div><!--/col-12-->
                </div><!--/row-->
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <input type="text" class="form-control" id="vorname" name="vorname" required placeholder="Vorname">
                      <span class="help-block" style="display: none;">Bitte geben Sie Ihren Vornamen ein.</span>
                    </div>
                  </div><!--/col-6-->
                  <div class="col-md-6">
                    <div class="form-group">
                      <input type="text" class="form-control" id="name" name="name" required placeholder="Name">
                      <span class="help-block" style="display: none;">Bitte geben Sie Ihren Namen ein.</span>
                    </div>
                  </div><!--/col-6-->
                </div><!--/row-->
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <input type="text" class="form-control" id="strasse" name="strasse" required placeholder="Strasse">
                      <span class="help-block" style="display: none;">Bitte geben Sie Ihre Strasse ein.</span>
                    </div>
                  </div><!--/col-5-->
                  <div class="col-md-2">
                    <div class="form-group">
                      <input type="text" class="form-control" id="plz" name="plz" required placeholder="PLZ">
                      <span class="help-block" style="display: none;">Bitte geben Sie Ihre Postleitzahl ein.</span>
                    </div>
                  </div><!--/col-2-->
                  <div class="col-md-4">
                    <div class="form-group">
                      <input type="text" class="form-control" id="ort" name="ort" required placeholder="Ort">
                      <span class="help-block" style="display: none;">Bitte geben Sie Ihren Ort ein.</span>
                    </div>
                  </div><!--/col-4-->
                </div><!--/row-->
                <div class="row">
                  <div class="col-md-8">
                    <div class="form-group">
                      <input type="email" class="form-control" id="email" name="email" required placeholder="E-Mail Adresse">
                      <span class="help-block" style="display: none;">Bitte geben Sie eine g&uumltige E-Mail Adresse ein.</span>
                    </div>
                  </div><!--/col-8-->
                  <div class="col-md-4">
                    <div class="form-group">
                      <input type="text" class="form-control" id="telefon" name="telefon" required placeholder="Telefon">
                      <span class="help-block" style="display: none;">Bitte geben Sie Ihren Ort ein.</span>
                    </div>
                  </div><!--/col-4-->
                </div><!--/row-->
                <div class="row">
                  <div class="col-md-5">
                    <div class="form-group">
                      <tr id='artikel0' data-id="0">
                        <td data-name="draeksak_artikel" data-type="select">
                          <select name="draeksak_artikel" class="form-control">
                            <option value"1">Auswahl Produkt</option>
                            <option value"2">Dr&aumlksak 1m3, CHF 37.00/Stk.</option>
                            <option value"3">Dr&aumlksak 1m3, inkl. Abholung und Entsorgung (CHF 210.00/Stk.)</option>
                          </select>
                        </td>
                      </tr>
                    </div>
                  </div><!--/col-5-->
                  <div class="col-md-3">
                    <div class="form-group">
                      <input type="text" class="form-control" id="anzahl" name="anzahl" required placeholder="Anzahl">
                      <span class="help-block" style="display: none;">Anzahl Produkt</span>
                    </div>
                  </div><!--/col-3-->
                  <div class="col-md-4">
                    <div class="form-group">
                      <tr id='lieferung0' data-id="1">
                        <td data-name="lieferung" data-type="select">
                          <select name="lieferung" class="form-control">
                            <option value"1">Lieferung</option>
                            <option value"2">Ja, per Post senden (Porto CHF 10.00/Stk.)</option>
                            <option value"3">Nein, ich hole den Dr&aumlksak vor Ort ab.</option>
                          </select>
                        </td>
                      </tr>
                    </div>
                  </div><!--/col-4-->
                </div><!--/row-->
                <div class="form-group">
                  <textarea rows="10" cols="100" class="form-control" id="message" name="message" required placeholder="Geben Sie hier Ihre Nachricht ein, falls erw&#252;nscht."></textarea>
                  <span class="help-block" style="display: none;">Bitte geben Sie eine Nachricht ein.</span>
                </div>              
                <button type="submit" class="btn btn-primary btn-lg" style="display: block; margin-top: 10px;">Bestellen</button>
              </div><!--/container-fluid-->  
            </form> <!--/form-->
          </div><!-- End of Modal body -->
        </div><!-- End of Modal content -->
      </div><!-- End of Modal dialog -->
    </div><!-- End of Modal -->

And my .js file:

$(function() {

// Get the form.
var form = $('#ajax');

// Get the messages div.
var formMessages = $('#form-messages');

// Set up an event listener for the contact form.
$(form).submit(function(e) {
    // Stop the browser from submitting the form.
    e.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    })
    .done(function(response) {
        // Make sure that the formMessages div has the 'success' class.
        $(formMessages).removeClass('error');
        $(formMessages).addClass('success');

        // Set the message text.
        $(formMessages).text(response);

        // Clear the form.
        $('#firma').val('');
        $('#vorname').val('');
        $('#name').val('');
        $('#strasse').val('');
        $('#plz').val('');
        $('#ort').val('');
        $('#email').val('');
        $('#telefon').val('');
        $('#draeksak_artikel').val('');
        $('#anzahl').val('');
        $('#lieferung').val('');
        $('#message').val('');
    })
    .fail(function(data) {
        // Make sure that the formMessages div has the 'error' class.
        $(formMessages).removeClass('success');
        $(formMessages).addClass('error');

        // Set the message text.
        if (data.responseText !== '') {
            $(formMessages).text(data.responseText);
        } else {
            $(formMessages).text('Ups! Leider ist ein Fehler aufgetreten und Ihre Bestellung konnte nicht versendet werden.');
        }
    });

}); });

And the php file, although that should be fine I guess:

<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection

// Only process POST requests.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $firma = strip_tags(trim($_POST["firma"]));
$firma = str_replace(array("","
"),array(" "," "),$firma);
    $vorname = strip_tags(trim($_POST["vorname"]));
$vorname = str_replace(array("","
"),array(" "," "),$vorname);
    $name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("","
"),array(" "," "),$name);
    $strasse = strip_tags(trim($_POST["strasse"]));
$strasse = str_replace(array("","
"),array(" "," "),$strasse);
    $plz = strip_tags(trim($_POST["plz"]));
$plz = str_replace(array("","
"),array(" "," "),$plz);
    $ort = strip_tags(trim($_POST["ort"]));
$ort = str_replace(array("","
"),array(" "," "),$ort);

    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);

    $telefon = strip_tags(trim($_POST["telefon"]));
$telefon = str_replace(array("","
"),array(" "," "),$telefon);

    $draeksak_artikel = trim($_POST["draeksak_artikel"]);
    $anzahl = trim($_POST["anzahl"]);
    $lieferung = trim($_POST["lieferung"]);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if ( empty($vorname) OR empty($name) OR empty($strasse) OR empty($plz) OR empty($ort)
        OR empty($email) OR empty($telefon) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Ups! Leider ist ein Fehler aufgetreten. Bitte stellen Sie sicher, dass Sie alle Felder korrekt eingesetzt haben.";
        exit;
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "asymmetrisch@gmail.com";

    // Set the email subject.
    $subject = "Bestellung Draeksak von unserer Webseite: $firma, $vorname, $name";

    // Build the email content.
    $email_content = "Firma: $firma
";
    $email_content .= "Vorname: $vorname
";
    $email_content .= "Name: $name
";
    $email_content .= "Strasse: $strasse
";
    $email_content .= "PLZ: $plz
";
    $email_content .= "Ort: $ort
";
    $email_content .= "Telefon: $telefon
";
    $email_content .= "Email: $email

";
    $email_content .= "Artikel: $draeksak_artikel
";
    $email_content .= "Anzahl: $anzahl
";
    $email_content .= "Lieferung: $lieferung
";
    $email_content .= "Nachricht:
$message
";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Danke Ihnen, wir haben Ihre Bestellung erhalten und bearbeiten diese sofort.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Ups! Etwas ist falsch gelaufen; leider konnte Ihre Bestellung nicht versendet werden.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "Es ist ein Problem aufgetreten. Ihre Bestellung konnte leider nicht versendet werden.";
} ?>

As one can see, I have a div id="form-messages" where either the success or error message should be posted (right now it is outside of the modal window, which would also be fine). In the form tag I included an id="ajax" which is then referenced in the .js file. But google chrome tells me, that this is an uncaught typeError: $ is not a function, it says. It's worth mentioning that I included the following files on the bottom of my html file:

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/ajax_dsshop.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<!-- bxSlider Javascript file -->
<script src="js/bx_slider/jquery.bxslider.min.js"></script>
<!-- bxSlider CSS file -->
<link href="js/bx_slider/jquery.bxslider.css" rel="stylesheet" />
<script>
  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥15 逻辑谓词和消解原理的运用
    • ¥15 三菱伺服电机按启动按钮有使能但不动作
    • ¥15 js,页面2返回页面1时定位进入的设备
    • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
    • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
    • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
    • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
    • ¥20 腾讯企业邮箱邮件可以恢复么
    • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
    • ¥15 错误 LNK2001 无法解析的外部符号