Reputation: 83
I am using Twitter Bootstrap 3 and using jQuery AJAX to send form data. Here is my code:
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
dataType: "json",
success: function (response) {
if (response.type = "error") {
$('#msgs').html("<div class='alert alert-danger'>"+response.text+"</div>");
} else {
$('#msgs').html("<div class='alert alert-success'>"+response.text+"</div>");
}
}
});
That should display error message with alert alert-danger class if type is error in json data & with alert alert-success if type is success in json data. But it displays both error and success messages with alert alert-danger.
What's wrong?
Upvotes: 1
Views: 11136
Reputation: 93
use this helper function , you can pass the message with the type of ('danger','success','info','warning') for it . it will generate bootstrap alert box for you .
var bsMSG = function (msg, type, seprator) {
html = '';
msg = (msg instanceof Array ?msg:[msg]);
type = type || 'success';
seprator = seprator || '<br/>';
b = '';
for (i = 0; i < msg.length; i++) {
html += b + msg[i];
b = seprator;
}
html = "<div class='alert alert-" + type + "'>" + html + "</div>";
return html;
};
// usage
if (response.type == "error") {
$('#msgs').html(bsMSG(response.text,'danger'));
}else{
$('#msgs').html(bsMSG(response.text'));
}
Upvotes: 0
Reputation: 98
I think you have to check like this in the if:
if (response.type == "error") {
$('#msgs').html("<div class='alert alert-danger'>"+response.text+"</div>");
} else {
$('#msgs').html("<div class='alert alert-success'>"+response.text+"</div>");
}
Upvotes: 6