I want to show alert of Bootstrap when ajax returns. But the alert flushed and then disappear very quickly. What is the right way to show an alert with Bootstrap? thanks.
$('#btn').click(function () {
var url = "add";
var data = $('#add_form').serializeArray().reduce(function(m,o){ m[o.name] = o.value; return m;}, {});
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data),
dataType: 'json',
contentType : 'application/json',
// async: false,
success: function(data2) {
if (data2.res == 1) {
showalert("Error", "alert-danger");
} else {
showalert("OK", "alert-success");
}
},
error: function(result)
{
},
timeout: 5000
});
});
function showalert(message, alerttype) {
$('#alert_placeholder').append('<div id="alertdiv" class="alert ' + alerttype + '" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + message + '</div>');
setTimeout(function() {
$("#alertdiv").remove();
}, 5000);
}
<div id = "alert_placeholder"></div>
...
<form id="add_form" method="post">
...
<div class="form-group row">
<div class="offset-2 col-10">
<!-- <button type="submit" id="btn" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Submit</button> -->
<button type="submit" id="btn" class="btn btn-primary">Submit</button>
</div>
</div>