Bootstrap Alert Message не работает - PullRequest
0 голосов
/ 14 мая 2018

Первый - я не эксперт в PHP, но просто знаю, как внести некоторые базовые изменения в контактную форму, используя PHP.

В этой контактной форме , когда я заполнил необходимые текстовые поляи нажмите кнопку отправки, которую он перенаправляет на contact.php с сообщением Contact form successfully submitted. Thank you, I will get back to you soon! вместо отображения сообщения внутри <div class="messages"></div> по запросу-интерпретатору. html

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>

contact.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();
                }
            }
        });
    }
})
});

1 Ответ

0 голосов
/ 14 мая 2018

Вы повторяете его (распечатываете) вместо того, чтобы возвращать ответ, измените его следующим образом: 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'];
}
...