user982124 user982124 - 1 month ago 5
Javascript Question

Update Bootstrap Alert Text from AJAX Request Result

I have a simple AJAX request that updates some PHP session variables based on some selections in a table. It fires off an AJAX request when they make their selections. At the moment if there's an error with the AJAX request I'm displaying a generic error message by showing a hidden Bootstrap Alert



<div id="alert_ajax_error" class="alert alert-danger text-center" role="alert" style="display:none">
There was an error updating your selections - please contact the Support Desk
</div>





I would now like to change the generic error message (There was an error updating your selections - please contact the Support Desk) to one that shows the error string returned from the AJAX request.

Here's my script:



$(document).ready(function() {
$('button.btn-success').click(function() {
var itemID = $(this).closest('tr').attr('id');
console.log(itemID);
// Create a reference to $(this) here:
$this = $(this);
$.post('updateSelections.php', {
itemID: itemID,
selectionType: 'yes'
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
console.log(ajaxError);
console.log('something was wrong with the ajax request');
$this.closest('tr').addClass("warning");
//make alert visible
$("#alert_ajax_error").show();
return; // stop executing this function any further
} else {
console.log('update successful - success add class to table row');
$this.closest('tr').addClass("success");
$this.closest('tr').removeClass("danger");
//$(this).closest('tr').attr('class','success');
}
}).fail(function(xhr) {
console.log('ajax request failed');
// no data available in this context
$this.closest('tr').addClass("warning");
//make alert visible
$("#alert_ajax_error").show();
});
});
});





The ajaxError variable contains the string I would like to use in my alert. Is it possible to somehow use this and insert it into the alert that is displayed?

Med Med
Answer

You can insert your response via:

$('#alert_ajax_error').html(data);
Comments