Alert on item brought in through ajax result?


Topic: Alert on item brought in through ajax result?

cfuller asked 4 years ago

Expected behavior After content is added to the DOM/page through an AJAX request, I would like to use mdb to classify it as an alert.

Actual behavior When I run mdb.Alert.getInstance(document.getElementById("testAlert")).show() (or .update)) I get an error message that "cannot read property 'show' of null.

I am a bit of a newbe so I might be missing something obvious. It seems like when I use the document.getElementById it is not paying attention to anything that has been added to the DOM after the initial load and I don't know how to make it do it.

Most of what I've done in the past I've used jQuery for, but I'm using using Bootstrap 5 so trying to avoid using jquery as much as I can moving forward. Using jquery, I used to use a $(document).arrive( selector, function() {}); command a lot to call activity on items that arrive dynamically on to the page. The app I'm building, most everything comes in dynamically based on user activity, I don't want to keep reloading the page.

Resources (screenshots, code snippets etc.)


Michał Duszak staff commented 4 years ago

Try reproducing this issue in snippets, as this problem may be caused by so many factors. You may be using script before you append testAlert into the DOM. Maybe you want to get data from an AJAX call and call Alert on button like in this snippet: https://mdbootstrap.com/snippets/standard/m-duszak/3117098


parson pro premium answered 4 years ago

I had the same issue and found a solution. Since the content is being added dynamically there isn't an instance of the alert yet so you need to create one.

const alertPopup = new mdb.Alert(document.getElementById('alert-danger'))
    alertPopup.update({
        position: "top-right",
        delay: 5000,
        autohide: true,
        width: "600px",
        offset: 20,
        stacking: false,
        appendToBody: false,
    });
    alertPopup.show()

Michał Duszak staff commented 4 years ago

Thank you for this answer!


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Free
  • Premium support: No
  • Technology: MDB Standard
  • MDB Version: MDB5 3.7.1
  • Device: PC
  • Browser: Chrome
  • OS: Win 10
  • Provided sample code: No
  • Provided link: No