user982124 user982124 - 1 year ago 121
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

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');
// 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('something was wrong with the ajax request');
//make alert visible
return; // stop executing this function any further
} else {
console.log('update successful - success add class to table row');
}).fail(function(xhr) {
console.log('ajax request failed');
// no data available in this context
//make alert visible

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 Source

You can insert your response via:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download