Welcome Guest, Not a member yet? Register   Sign In
Bootstrap Dynamic Modal View With AJAX
#4

(This post was last modified: 03-13-2016, 02:03 PM by PaulD. Edit Reason: Quick typo )

Hi,

It is actually very easy.

In your main view you have a single modal window view, something like:

Code:
<!-- Modal -->
<div class="modal fade" id="preview" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
 <div class="modal-dialog" role="document">
   <div class="modal-content">
     <div class="modal-header">
       <button type="button" class="close text-danger" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times; <small>Close</small></span></button>
     </div>
     <div class="modal-body" id="modal-content">
       <img class="loader" src="<?php echo base_url('images/loaders/loader1.gif'); ?>" alt="" /> Loading Preview...
     </div>
   </div>
 </div>
</div>

Your controller calls your view like normal, but include some javascript that, on click, loads the modal with a loader message, then opens the modal window, ajax's to get the real content (or error message), and then loads the modal content with that information.

Something like

Code:
<script>
jQuery(document).ready(function(){
"use strict";

// assign js function to class
$('.preview_product').click(preview);

function preview() {
event.preventDefault();
// collect data - either from forms or from data variables
var id = $(this).data('id');

// load the modal content with a loader gif and message
$('#modal-content').html('<img class="loader" src="/images/loaders/loader1.gif")." alt="" /> Loading Preview...');

// show modal window
$('#preview').modal('show');

// do the ajax bit
var post_data = {
'product_id': id,
};
$.post('ajax_get_preview'), post_data, function(theResponse){

// load the modal window with the relevant content returned
$('#modal-content').html(theResponse);
});
}

});
</script>

This is not necessarily working code, nor a full working example. The examples here are just simplified example bits from sites I have doing the same thing. My controller also loads the modal with the CSRF token for CSRF validation too. I also usually include some JS that updates the loader message should the ajax call fail. But as I said, have chopped this down for simplicity and added comments to help. One modal window - fired from a single class - content loaded through Ajax call to get content.

Once you get the hang of it, it is not only powerful, it really brings modal windows to life. I find myself using them more and more now, for all sorts of things.

Hope that helps.

Paul.
Reply


Messages In This Thread
RE: Bootstrap Dynamic Modal View With AJAX - by PaulD - 03-13-2016, 02:00 PM



Theme © iAndrew 2016 - Forum software by © MyBB