FAQ
AJAX with JQUERY modal
A great way to speed up your application is to load content after the page has loaded.
This way on page load you can limit your complex joins from your database.
One good example is you want to display content that loads in a popup.
# 1 > Create Action in Controller
-> CREATE AN ACTION (popup()) in your controller that will initially load App Controllers Pages
function popup() {
//light weight, doesn’t load anything
}
# 2 > Create Modal in View
-> Create a modal like you normally do in the view APP/View/Pages/popup.ctp
<li>
<!-- Button trigger modal -->
<button type=“button” class=“badge badge-primary badge-sm link-pointer” data-toggle=“modal” data-target=“#viewProjectsModal”>
Projects
</button>
</li>
<!-- viewProjectsModal Modal -->
<div class=“modal fade” id=“viewProjectsModal” tabindex=“-1” role=“dialog” aria-labelledby=“viewProjectsModalLabel” aria-hidden=“true”>
<div class=“modal-dialog” role=“document”>
<div class=“modal-content”>
<div class=“modal-header”>
<h5 class=“modal-title” id=“viewProjectsModalLabel”>Projects</h5>
<button type=“button” class=“close” data-dismiss=“modal” aria-label=“Close”>
<span aria-hidden=“true”>×</span>
</button>
</div>
<div class=“modal-body”>
<div id=“content”>
Loading...
</div>
</div>
<div class=“modal-footer”>
<button type=“button” class=“btn btn-secondary” data-dismiss=“modal”>Close</button>
<button type=“button” class=“btn btn-primary”>Save changes</button>
</div>
</div>
</div>
</div>
# 3 > Add Script for Ajax call
-> Add the following code in .js file OR in view <script>
$(“#viewProjectsModal”).on(“show.bs.modal”, function(e) {
//do this only when the modal is activated
$.ajax({
type: “POST”,
contentType: “application/x-www-form-urlencoded; charset=utf-8",
url: “<?= $this->webroot; ?>Pages/popupDisplay”,
data: “HELLO”,
success: function (data) {
$(‘#content’).html(data);
//alert(data); //used for testing
},
error: function (result) {
alert(“Error”);
}
});
});
</script>