kevin seda kevin seda - 5 months ago 33
jQuery Question

Ajax success/error message only displaying once

I have created a form using

php
ajax
and
JavaScript
.

With ajax I successfully managed to display an error/success message while staying on the same page.

It works alright if I use
console.log
to display the error/success message.

But I don't want to display the error message on the
console.log


so this is what I did:

$('form.form-style-4').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();

data[name] = value;
});

$.ajax({
url: url,
type: method,
data: data,
success: function(response) {

console.log(response);
$('#success-message').html(response);
setTimeout(function() {
$('#success-message').fadeOut('slow');
}, 3000);



}
});

return false;


});


As you can see I created a div called
#success-message
the reponse is displayed in this div.

My problem now is It only shows the error or success message just once, unless I reload the page.

So my first idea was to reload the entire page every time someone clicks on submit, with javascript like this:

setTimeout(function() {
window.location.reload(1);
}, 2000);


But I don't think that is the way to go.

Answer

You have show you message success-message first

$('#success-message').html(response).show();
Comments