Display admin_notice error message form jQuery event

Thanks to Douglas.Sesar for pointing me in the right direction. Much appreciated! This is what I did…

First put the following id in the title heading of the plugin. I am adding the admin message html (via jQuery) directly after this heading.

<h1 id="my-admin-message">My Plugin Title</h1>

My jQuery function:

function fnDisplayAdminMessage(adminMessage, adminMessageColor) {
jQuery.ajax({
    type: 'POST',
    url: myAjax.ajaxurl,
    success: function(response) {
        jQuery('#my-admin-message').after('<div class="error notice is-dismissible"><p>' + adminMessage + '</p><button id="my-dismiss-admin-message" class="notice-dismiss" type="button"><span class="screen-reader-text">Dismiss this notice.</span></button></div>');
        jQuery("#my-dismiss-admin-message").click(function(event) {
            event.preventDefault();
            jQuery('.' + 'error').fadeTo(100, 0, function() {
                jQuery('.' + 'error').slideUp(100, function() {
                    jQuery('.' + 'error').remove();
                });
            });
        });
        switch (adminMessageColor) {
        case 'yellow':
            jQuery("div.error").css("border-left", "4px solid #ffba00");
            break;
        case 'red':
            jQuery("div.error").css("border-left", "4px solid #dd3d36");
            break;
        default:
            jQuery("div.error").css("border-left", "4px solid #7ad03a");
        }
    }
});
}

And my call:

fnDisplayAdminMessage('There was an error.', 'red');

I made it so I am always using the ‘error’ admin notice, and just changing the color.

Lastly, a function to remove the message:

function fnRemoveAdminMessage() {
// check if there is an admin message displayed, if so then remove it
if (jQuery("div.error").length) {
    jQuery("div.error").fadeTo(100, 0, function() {
        jQuery("div.error").slideUp(100, function() {
            jQuery("div.error").remove();
        });
    });
}
}

I hope someone else finds this useful.

Leave a Comment