Skip to content

Instantly share code, notes, and snippets.

@davedkg
Created September 14, 2021 03:36
Show Gist options
  • Save davedkg/35da7d32ac07ce58ecde08ff9d0a6e7b to your computer and use it in GitHub Desktop.
Save davedkg/35da7d32ac07ce58ecde08ff9d0a6e7b to your computer and use it in GitHub Desktop.
AJAX Modal using jQuery
jQuery.fn.ajaxModal = function() {
this.each(function() {
var el = $(this);
el.click(function(event) {
// show loading overlay (optional)
$("<div class='loading' id='loading'/>").appendTo('body');
$.ajax({
url: $(this).attr('href'),
success: function(newHTML, textStatus, jqXHR) {
// remove loading overlay
$("#loading").remove();
// append modal to body and open
$(newHTML).appendTo('body').modal({showClose: false, closeExisting: true});
},
error: function(jqXHR, textStatus, errorThrown) {
// remove loading overlay
$( "#loading" ).remove();
// show toast error message
$.toast({
position: 'bottom-left',
text: "Unable to load modal.",
icon: 'error',
showHideTransition: 'fade',
loader: false,
allowToastClose: false
});
}
});
return false;
});
});
}
// <a href="/modal" rel="ajax:modal">Show AJAX Modal</a>
$(document).ready(function() {
$('*[rel="ajax:modal"]').ajaxModal();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment