【问题标题】:Bootstrap Alert Message not working引导警报消息不起作用
【发布时间】:2018-10-24 10:38:13
【问题描述】:

首先 - 我不是 PHP 专家,但只知道如何使用 PHP 在联系表单中进行一些基本更改。

在这个contact form 上,当我填写所需的文本字段并点击提交按钮时,它会重定向到带有Contact form successfully submitted. Thank you, I will get back to you soon! 消息的contact.php,而不是在request-interpreter.html 上的<div class="messages"></div> 内显示消息

HTML(表单)

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

    <div class="messages"></div> <----- displays alert messages

    <div class="controls">
        <div class="row-form">
            <div class="col-md-6">
                <p class="text-req"><strong>*</strong> These fields are required. </p>
            </div>
        </div>
        <div class="row-form">
            <div class="col-md-6">
                <div class="form-group">
                    <input id="form_name" type="text" name="name" class="form-control" placeholder="First name *" required="required" data-error="First name is required." tabindex="1">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <input id="form_email" type="email" name="email" class="form-control" placeholder="Email *" required="required" data-error="Your email address is required." tabindex="3">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
        </div>
        <div class="row-form">
            <div class="col-md-6">
                <div class="form-group">
                    <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Last name *" required="required" data-error="Last name is required." tabindex="2">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Phone *" required="required" data-error="Your phone number is required." tabindex="4">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
        </div>
        <div class="row-form">
            <div class="col-md-12">
                <div class="form-group">
                    <textarea id="form_message" name="message" class="form-control" placeholder="Leave a message for us *" rows="4" required="required" data-error="Your important message is required." tabindex="5"></textarea>
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-6">
                <input type="submit" class="btn btn-success btn-send" value="Send Request" tabindex="6">
            </div>
        </div>
    </div>
</form>

联系人.php

<?php
// an email address that will be in the From field of the email.
$from = 'Contact form';

// an email address that will receive the email with the output of the form
$sendTo = $_POST['email'];

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

// if you are not debugging and don't need error reporting, turn this off by 
error_reporting(0);
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 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'];
}

AJAX 提醒消息

$(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); <------ it should display the alert message, but its not working.
                    // empty the form
                    $('#contact-form')[0].reset();
                }
            }
        });
    }
})
});

【问题讨论】:

    标签: javascript php html forms ajaxform


    【解决方案1】:

    您正在回显它(打印它)而不是返回响应,请在您的 Contact.php 中像这样更改它

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);
    
    header('Content-Type: application/json');
    
    return $encoded;
    }
    // else just display the message
    else {
    return $responseArray['message'];
    }
    

    【讨论】:

    • 谢谢!在我更新了你的代码之后。我能够收到电子邮件,但没有收到警报消息。它重定向到没有消息的contact.php 页面。警告消息仍然没有显示在消息 div 中。
    • 尝试将if (!e.isDefaultPrevented()) 替换为if (e.isDefaultPrevented()) 为什么设置为not,它应该检查真实值对吗?
    • 我更新了,还是不会在消息 div 中显示消息。
    • 只做e.preventDefault();而不是返回false;我猜,检查什么有效,您正在阻止导致您的操作进入 php 页面的默认操作,还要检查浏览器中的控制台错误
    • 记住我不是 PHP 专家。你是什​​么意思而不是return false;?因为我从e-preventDefault(); 中删除了! 仍然没有工作。
    猜你喜欢
    • 1970-01-01
    • 2017-04-12
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多