У меня есть контактная форма, которая одинакова на нескольких страницах, поэтому у меня есть php-скрипт, который вызывается всеми страницами, на которых есть контактная форма.Скрипт работает отлично, обрабатывает recaptcha, отправляет электронную почту и все хорошо.Но каждый раз, когда он запускается, после предупреждения, сообщающего пользователю, что отправка почты прошла успешно, он открывает пустую страницу с URL-адресом php-скрипта.Я просто хочу, чтобы страница оставалась там, где она была - отображать предупреждение об успехе (или неудаче), пользователь нажимает «ОК», и он смотрит на ту же страницу.Вот форма:
<div class="col-md-7">
<h2>Contact Us</h2> Got a question ? Feedback? Awesome!
<form class="mt-4 mt-md-0" role="form" action="/php/mail.php" method="post" >
<div class="form-group">
<label for="name" class="sr-only control-label">Name</label>
<input class="form-control bg-faded-4" id="form_name" type="text" name="name" placeholder="Please enter your name *" required="required" data-error="Name is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="email" class="sr-only control-label">Email</label>
<input class="form-control bg-faded-4" 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 class="form-group">
<label for="message" class="sr-only control-label">Message</label>
<textarea class="form-control bg-faded-4" id="form_message" name="message" 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 class="form-group">
<div class="row" style="margin-bottom:30px;">
<span class="msg-error error"></span>
<div class="g-recaptcha" data-sitekey="<MY_SITE_KEY>" style="padding-left: 15px"></div>
</div>
</div>
<button type="submit" class="btn btn-secondary btn-sm mt-2" name="submit" id="submit">Send Message</button>
</form>
</div>
</div>
А вот сценарий php:
<?php
$errName = "";
$errEmail = "";
$errMessage = "";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'myform@mysite.com';
$to = 'myemail@gmail.com';
$subject = 'Message from Contact Form ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
else
$sender_name = stripslashes($_POST["name"]);
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
else
$sender_email = stripslashes($_POST["email"]);
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
else
$sender_message = stripslashes($_POST["message"]);
$response = $_POST["g-recaptcha-response"];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => '<MY_SECRET_KEY>',
'response' => $_POST["g-recaptcha-response"]
);
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
// If there are no errors, send the email
if ($captcha_success->success==false) {
echo "<p>You are a bot! Go away!</p>";
} else if ( ($errName != "") ) {
echo "<script type='text/javascript'>alert('Please enter your name.'); </script>";
} else if ($errEmail != "") {
echo "<script type='text/javascript'>alert('You must enter a valid email address. Please try again.');</script>";
} else if ( $errMessage != "") {
echo "<script type='text/javascript'>alert('You must enter some message text. Please try again.');</script>";
} else {
// 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
$mailResponse = mail($to, $subject, $message, implode("\n", $headers));
if ( $mailResponse == 1 ) {
echo "<script type='text/javascript'>alert('We\'ll be in touch!'); </script>";
} else {
echo "<script type='text/javascript'>alert('Error sending message. Please try again.');</script>";
}
}
?>
Я уверен, что это действительно ужасный код php, на самом деле он не занимался программированием php.Но моя настоящая проблема в том, что это пустое окно появляется после того, как форма обработана php-файлом - как я могу это остановить?
Спасибо .....
Итак, последняя строкаскрипт php теперь читает:
header('Location:http://sq36.cawgcap.org');
Но вот что я вижу.Перед нажатием кнопки «Отправить»: И после обработки формы:
Как только я нажму "ОК" в уведомлении, яслева, глядя на пустую страницу с адресной строкой, показывающей расположение скрипта php.