I have a contact form that uses Ajax. After submitting the data (using a PHP script) the form displays a message that the data was sent. However, the display doesn’t disappear after a delay. It just has an “x” for the user to close it. I think I found a way for it to fade out but the page (form?) needs to be reset to use it again. Here is the script for the message.
$(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">×</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);
$('.messages').delay(5000).fadeOut(); // *********** ADDED BY ME ***************
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
I know $('#contact-form')[0].reset();
should reset it but it doesn’t allow it to run again w/o reloading the page (defeating the purpose of Ajax). I have also tried $("#contact-form").trigger('reset');
and document.getElementById('contact-form').reset()
but with the same result.
If I remove the line that says “ADDED BY ME” it works fine but the user has to click on the “x” to close the message. I would like it if the message would display for a period of time (i.e., 5 seconds) and then disappear. Is this possible?