Closing notifications in Bootstrap 5.1 with the help of Ajax

I am utilizing bootstrap 5.1 alerts to display custom messages after an Ajax call. I also want the ability to dismiss the alert as necessary, which can be done with a dismiss button provided by bootstrap.

Below is the PHP code I am using :

<div class="alert alert-warning alert-dismissible" role="alert" style="display:none;" id="message-response-given">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

And here is the relevant JavaScript for handling the Ajax response :

document.getElementById("message-response-given").innerHTML = res.message;
$('#message-response-given').fadeIn();

This successfully displays the message but does not show the dismissal button after the Ajax call.

I have gone through this information (bootstrap alerts, same link as above) :

Once an alert is dismissed, it is completely removed from the page structure. This may cause issues for keyboard users since their focus will shift suddenly and might reset to the beginning of the page depending on the browser. To address this, it's recommended to include additional JavaScript that listens for the closed.bs.alert event and programmatically sets focus() to the most suitable location in the page. If you intend to move focus to a non-interactive element that doesn't usually receive focus, remember to add tabindex="-1" to the element.

However, I am unsure how to implement this....

Answer №1

When updating the button HTML, avoid overwriting it by using:

document.getElementById("message-response-given").innerHTML = res.message;

Instead of replacing the content, consider using append method and passing the message as a parameter. With jQuery, you can simplify your script into a chained one-liner like this:

$('#message-response-given').append(res.message).fadeIn();

Here's an example:

$('#message-response-given').append("message").fadeIn();
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72101d1d06010600130232475c45305141">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhModel-8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<div class="alert alert-warning alert-dismissible" role="alert" style="display:none;" id="message-response-given">
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>


<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c3e3333282f282e3d2c1c69706d726f">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOgBgP+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AngularJS with angular-google-maps to easily add markers through a form and locate your position with one click

I'm attempting to replicate the functionality demonstrated on since it fulfills 90% of my requirements. However, I'm facing some difficulties. While I can retrieve my location and log it in the console, a marker is not appearing on the map. Add ...

Utilizing AngularJS to make AJAX requests upon selection in order to populate another dropdown menu

Is there anyone who has experience working with AngularJS and using select dropdowns to dynamically populate another dropdown on the page based on a selection? We are currently utilizing a service to populate one Select dropdown. However, we also have ano ...

Is it possible to dynamically choose between GET and POST methods for an AJAX request?

Consider the following code snippet which intercepts the form submission event from two different forms. $("#aaa, #bbb").submit(function(e) { e.preventDefault(); var form = $(this); var url = form.attr('action'); $.ajax({ ...

``In JavaScript, the ternary conditional operator is a useful

I am looking to implement the following logic using a JavaScript ternary operation. Do you think it's feasible? condition1 ? console.log("condition1 pass") : condition2 ? console.log("condition2 pass") : console.log("It is different"); ...

Populate a table with data from a different table using JavaScript

On my webpage, I have a grid of selectable divs that are defined by rows and columns. When I select certain divs, it creates what I'll call "table Copy", a three-dimensional table. If I select different elements, another three-dimensional table calle ...

When attempting to update my avatar using client.user.setAvatar(), the desired changes fail to take effect

Currently, I am attempting to update the bot avatar with a specific user's avatar, but I seem to be encountering some difficulties. I have attempted the following code: client.users.fetch('userid').then((user) => { client.user.setAva ...

One way to showcase a single piece of data without the need for looping is by utilizing the `

I am encountering an issue. Why does the insertAdjacentHTML("afterend") output keep looping? I only want to display "1" once, not repeatedly. var btn = document.getElementById("btnClick"); btn.addEventListener("click", function (e) { e.preventDefaul ...

Dynamically add index to attribute as it updates

Having an issue with my dynamic button element: <button v-on:click="changeRecord(element)" v-b-modal.modal-5>Aendern</button> This button is generated dynamically within a v-for loop. Instead of manually including the attribute name like v-b- ...

The asynchronous postback end does not function properly in Chrome when using ajax

I am encountering an issue with my sample app developed in ASP.NET 3.5. I have a loading GIF displayed on the master page while the page loads, which works fine on IE and Firefox but fails on Chrome. When I click the submit button, the server receives the ...

Disable the default controls on the Open Layers Bing Map

I am currently working on an App that utilizes Geolocation with Open Layers to load a Bing Map Layer. My goal is to enable touch-based zooming and remove the default zoom buttons. Additionally, I would like to relocate the 'i' button to prevent a ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

Leveraging the power of express, employing the await keyword, utilizing catch blocks, and utilizing the next

I am currently developing an express JS application that follows this routing style: router.post('/account/create', async function(req, res, next) { var account = await db.query(`query to check if account exists`).catch(next); if (accoun ...

Adjusting Media Queries according to the browser window's zoom level

Is there a way to detect the browser width dynamically? For instance, can I adjust the CSS styling based on zoom adjustments like ctrl + or ctrl -? By "box," I am referring to a perfectly square shape. So, when the browser width is 100%, I want a layout wi ...

Troubaling with AngularJS Routing issues

I am encountering an issue with my routing system. The "otherwise" case is functioning correctly, however, when I click on a menu item, the routing does not load the corresponding page automatically. Can someone assist me in identifying what is wrong with ...

What is the best way to save the values of all the input fields in a datatable, excluding any fields that are empty?

$('form').on('submit', function(e){ var form = this; // Encoding a set of form elements from all pages as an array of names and values var params = table.$('input').serializeArray(); // Iterating over all form ...

Is there a way to compare data before and after revalidation using useSWR?

With the use of Next.js and through the implementation of useSWR, data is fetched from an endpoint every 30 seconds using an automatic revalidation interval (https://swr.vercel.app/docs/revalidation#revalidate-on-interval). Within the retrieved data, there ...

Dealing with an unexpected token error in JSON? Learn how to properly handle removing special characters like quotation marks and line breaks to

After receiving a JSON response from the server during page load, I successfully populate it on the page using Handlebars.js. However, I am facing difficulties in storing this JSON object in a JavaScript object. Here is what I tried: var jsObject = "{{o ...

Next.js is able to generate a unique URL that strictly handles code execution without any visual elements

Currently, I am in the process of developing a new website using NextJS. One issue that has come up involves a password reset verification endpoint. After a user initiates a password reset, it is sent to the API for processing and then redirected back to ...

What's the issue with my jQuery AJAX script?

I am experiencing an issue with my ajax pages using jQuery to retrieve content. Only one page seems to be working properly, even though I have multiple pages set up. How can I resolve this problem? $(document).ready(function() { $('.lazy_content& ...

Poorly formatted code in VueJS when using Visual Studio Code

After reinstalling Windows and installing Visual Studio Code along with Prettier, I am facing an issue where the formatting is not up to par. Below is an example showcasing the difference between how it looks versus how it should look. Incorrect Formatting ...