Это форма для восстановления пароля через HTML-страницу, которая отправляет данные в файл PHP через AJAX. С кодом все в порядке, за исключением того, что после отправки и получения ответа поля ввода формы не очищаются. Я искал в Интернете последние 4 часа и нашел слишком много строк кода для этого, но ни одна из них, похоже, не работает. Помогите плз в этом вопросе :) хорошего дня.
$(function() {
/////////////////////////////////////////////////////////'Form ID' & 'Element Name' /////////////////////////////////////////
// Get the form.
var form = $('#emailform');
// Get the messages div.
var formMessages = $('#formresults');
// 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.
// $('#email1').val('');
//var email = $('input[name=#email]').val("");
//document.getElementById("emailform").reset();
//$('#emailform')[0].reset();
//$('input:text').val('');
//$('#emailform input[type=text]').val('');
//setTimeout(function(){
//$('input,textarea','#emailform').val(''); //clearing inputs
//},1);
})
.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('Oops! An error occured and your message could not be sent.');
}
});
});
});<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>AJAX Contact Form Demo</title>
<link rel = "stylesheet" href = "style.css">
</head>
<body>
<div id = "page-wrapper">
<h1>AJAX Contact Form Demo</h1>
<div id = "formresults"></div>
<form id = "emailform" name = "emailform1" method = "post" action = "exa.php">
<table align = "center">
<tr><td><div class = "input-append"><input type = "text" name = "email" id = "email1" class = "input-xlarge" placeholder = "email" maxlength = "100" /><span class = "add-on"><li class = "icon-envelope"></li></span></div></td></tr>
</table>
<!-- <hr /> -->
<center><input type = "submit" name = "Forget" id = "btn" class = "btn btn-primary Loading-btn" value = "ٍSend" data-loading-text = "Sending ..." /></center>
</form>
</div>
<script src = "ajax/jquery-2.1.0.min.js"></script>
<script src = "ajax/app.js"></script>
</body>
</html><?php
// Get Access to data base
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$email = $_POST["email"];
// Check that data was sent to the mailer.
if ( empty($email) ) {
// Set a 400 (bad request) response code and exit.
http_response_code(100);
echo "BLABLABLA.";
exit;
}
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
// Set a 400 (bad request) response code and exit.
http_response_code(200);
echo "BLABLABLA.";
exit;
}
if (@mysql_num_rows(mysql_query("SELECT `id` FROM `accounts` WHERE `email`='$email'")) < 1) {
// Set a 400 (bad request) response code and exit.
http_response_code(300);
echo "BLABLABLA.";
exit;
}
$row_user = @mysql_fetch_array(mysql_query("SELECT * FROM `accounts` WHERE `email`='$email'"));
////////////////////////////
$password = $row_user['pass'];
$to = $row_user['email'];
$subject = "Your Recovered Password";
$message = "Please use this password to login: " . $password;
$headers = "From : [email protected]";
// Send the email.
if (mail($to, $subject, $message, $headers)) {
// Set a 200 (okay) response code.
http_response_code(400);
echo "BLABLABLA.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "BLABLABLA.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(600);
echo "There was a problem with your submission, please try again.";
}
?>
@ WebCode.ie не работал :(
Ты что-то не так делаешь так. Приведенный выше код на 100% очищает все заполненные элементы формы в форме.
@ WebCode.ie вот что меня бесит. это работает для всех, но не для меня :(



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы можете использовать функцию JavaScript .reset() в элементе формы, которая очистит все поля ввода.
Я нашел ответ, просто удалил http_response_code () для всех операторов if.
Спасибо всем за вашу помощь. Теперь я могу спать, зная, что мой день не потрачен зря :)
document.getElementById ("emailform"). reset ();