Во-первых, php scrips запускается на стороне сервера, а js - на стороне клиента, поэтому невозможно сделать то, что вы пытаетесь сделать, без того, чтобы обе стороны "разговаривали" друг с другом.Я вижу, что вы создали AJAX, это один из способов сделать это общение.
Второе: ваш PHP-скрипт должен отправить ответ на AJAX.Я считаю, что общий способ сделать это - использовать ответ JSON.В конце вашего .php вы должны поместить следующий код:
header('Content-Type: application/json');
echo json_encode($status);
Теперь вам нужно заставить js прочитать ответ и что-то с ним сделать.Вам нужно будет добавить ответ в форму, чтобы js знал, что вы будете использовать его как-то
$(document).ready(function() {
// bind 'email-form' and provide a simple callback function
$('#email-form').ajaxForm(function(response) {
console.log(response); //here you will have your $status variable, but readable from js.
// now you shoul call the function to make the changes on the page
snackbarfunction(response);
});
});
Obs1: я помещаю console.log('response')
, потому что $status
может быть неresponse
переменная, она может быть внутри ответа, например: response.data
Я позволил себе изменить вашу функцию для использования переменной JS:
function snackbarfunction(response) {
if(response == "Done"){
var z = document.getElementById("snackbardone");
z.className = "show";
setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
}else if(response == "Duplicated"){
var y = document.getElementById("snackbarrepeated");
y.className = "show";
setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
}else{
var x = document.getElementById("snackbarfailed");
x.className = "show";
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
}
ОБНОВЛЕНИЯ
Создайте новый файл в том же каталоге формы:
<?php
require_once "DB.php";
$status = null;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$status = "s";
$email = $_POST['email'];
if(filter_var($email , FILTER_VALIDATE_EMAIL) && htmlspecialchars($_POST['email']))
{
$conn = connectToDB();
if( ! userGet($email , $conn))
{
userSave($email , $conn) ? $status = "Done" : $status = "Not-Done";
}
else
{
$status = "Duplicated";
}
}
}
header('Content-Type: application/json');
echo json_encode($status);
Ваша страница формы:
The rest of the file...
<form class="news-letter" id="email-form" method="post" action="send_mail.php">
<div class="subscribe-hide">
<input class="form-control" type="email" id="subscribe-email" name="email" placeholder="Email Address" required>
<button onclick="snackbarfunction()" id="subscribe-submit" class="btn"><i class="fa fa-envelope"></i>
</button>
<span id="subscribe-loading" class="btn"> <i class="fa fa-refresh fa-spin"></i> </span>
<div id="snackbarrepeated">Email already exists.</div>
<div id="snackbardone">Successful, Thanks.</div>
<div id="snackbarfailed">Unsuccessful, Please try again.</div>
</div>
</form>
<br>
<p class="section-description">
We Will Notify You!
</p><!-- /.section-description -->
<br>
</div>
</div>
<br> <br>
</div>
<!-- /.container -->
</div>
<!-- /.pattern -->
</section>
<script>
function snackbarfunction(response) {
if(response == "Done"){
var z = document.getElementById("snackbardone");
z.classList.add('show');
setTimeout(function(){ z.classList.remove('show'); }, 3000);
}else if(response == "Duplicated"){
var y = document.getElementById("snackbarrepeated");
y.classList.add('show');
setTimeout(function(){ y.classList.remove('show'); }, 3000);
}else{
var x = document.getElementById("snackbarfailed");
x.classList.add('show');
setTimeout(function(){ x.classList.remove('show'); }, 3000);
}
}
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'email-form' and provide a simple callback function
$('#email-form').ajaxForm(function(response) {
console.log(response); //here you will have your $status variable, but readable from js.
// now you shoul call the function to make the changes on the page
snackbarfunction(response);
});
});
</script>
</body>
</html>
Я изменяю className
наclassList
потому что, если элемент имеет другой класс, он будет заменен.Как это:
<div id="a" class="a b"></div>
<script>
document.getElementById("a").className = "c"; // The element would lose class a and b and only have c
document.getElementById("a").classList.add("c");//The element would have class a,b and c
</script>
```
Obs2: The code may need some changes, like i pointed on obs1, but if you debug the code you should have no problem with that.