0

I have a master container php file with a div container. Initially, the div container doesn't have any content or html children by default when page is loaded. I use JQuery to load php files to this div container when the user clicks a navigation item in the navbar.

landingpage.php

<?php
require_once 'navbar.php';
?>

<!DOCTYPE html>
<html>
<head>
    <title>Admin | Dashboard</title>
    <link rel="stylesheet" href="css/dashboard_admin.css">
</head>
<body>
<div class="wrapper">
    <!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
    <div class="container" id="content_container">
        <div class="div_dashboardLabel" id="dashboard_Label">
            <h2 id="label_Dashboard">Admin Dashboard</h2>
        </div>
    </div>
    <!-- END OF CONTENT CONTAINER-->
</div>
<!-- end of wrapper-->

<script src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
    var user = '<?php echo json_encode($user);?>';
    var role = '<?php echo json_encode($role); ?>';
</script>
<script src="js/landingpage.js"></script>

</body>
</html>

landingpage.js

/* GLOBAL VARIABLES WITHIN THIS DOCUMENT*/
var div_content_container = $("#content_container");
var navitem_dashboard = $("#admin_dashboard");
var navitem_admin_account_management = $("#admin_accountmanagement");

var userObj = JSON.parse(user);
var roleObj = JSON.parse(role);
var logout = $('#logout');
/* END */

$(document).ready(function(){
    loadDashboard(); // dashboard is loaded as default view.
    navitem_admin_account_management.on("click",loadAccountManagement);
});

function loadDashboard() {
    var url_admin_dashboard = 'view/admin_dashboard.php';
    var url_teacher_dashboard = 'view/teacher_dashboard.php';
    var url_student_dashboard = 'view/student_dashboard.php';
    div_content_container.html('');
    if (roleObj.rolename === 'Administrator') {
        div_content_container.load(url_admin_dashboard);
    } else if (roleObj.rolename === 'Teacher') {
        div_content_container.load(url_teacher_dashboard);
    } else if (roleObj.rolename === 'Student') {
        div_content_container.load(url_student_dashboard);
    }
}

function loadAccountManagement(){
    var url = 'view/admin_accountmanagement.php';
    div_content_container.html('');
    div_content_container.load(url);
}

Everything works as expected for landingpage.php which uses landingpage.js for the front end. No problem.

The problem is when admin_accountmanagement.php file is loaded in div_content_container. The JS of admin_account_management.php doesn't seem to bind to elements:

function loadAccountManagement(){
    var url = 'view/admin_accountmanagement.php'; // has its JS file
    div_content_container.html('');
    div_content_container.load(url);
}

For example, let's take url which is 'view/admin_accountmanagement.php' This page gets loaded within div_content_container when user clicks a navbar item Account Management

as in

<div class="wrapper">
    <!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
    <div class="container" id="content_container">
        <!-- view/admin_accountmanagement.php loaded here --> 
    </div>
    <!-- END OF CONTENT CONTAINER-->
</div>

There are no problems displaying the page or replacing the current element contained in the div_content_container. The problem is, the JS file attached to view/admin_accountmanagement.php doesn't seem to apply when view/admin_accountmanagement.php page is loaded in div_content_container

The view/admin_accountmanagement.php is loaded but the click events binded to the elements of view/admin_accountmanagement.php doesn't work. I know this because I tried to display an alert() message on $(document).ready()

admin_accountmanagement.php

<body>
    <div>
    <button class="button" id="btn_AddUser">
        Add New User
    </button>
    </div>
    <script src="js/admin_accountmanagement.js"></script> <!-- this JS doesn't seem to get binded when this page is loaded in the div_content_container -->
</body>

admin_accountmanagement.js

var btn_add_user = $('#btn_AddUser');

$(document).ready(function(){
    alert("TEST"); //doesn't work no alert message.
    btn_add_user.on("click",test); //doesn't work no alert message
});

function test(){
    alert("testing"); //doesn't work. no alert message
}

I'm only able to display the page but when I click on the <button id="btn_AddUser"> nothing happens.

How can I solve this given the how I structured the loading of pages to div_content_container?

Thanks in advance.

heisenberg
  • 1,784
  • 4
  • 33
  • 62
  • try using `window.load()` instead of `document.ready()`. – vikscool May 14 '18 at 05:09
  • @vikscool I tried your suggestion and replaced `$(document).ready()` of **admin_accountmanagement.js** with `$(window).load(function(){ alert("TEST); })` but didn't work. – heisenberg May 14 '18 at 05:18
  • do you have error in your console?? – לבני מלכה May 14 '18 at 05:20
  • 1
    The problem is how you bind your click events. If you do `btn_add_user.on("click",test);`, it will only bind that event if the element exists on page load (which it doesn't, since you're using ajax to load it after). You need to bind it something like: `$('body').on('click', 'the-button-identifier', test);`. That will bind the event to the body and then, it will add it on all elements that matches the "the-button-identifier" _as they appear_ in the DOM. – M. Eriksson May 14 '18 at 05:26
  • @לבנימלכה I'm not getting any error. I'll try to inspect further. – heisenberg May 14 '18 at 05:26
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – M. Eriksson May 14 '18 at 05:27
  • I asked you that maybe you dont have script to jquery or something – לבני מלכה May 14 '18 at 05:27
  • @לבנימלכה - Since the OP can load the other pages using jQuery, I think it's safe to say it's included correctly. – M. Eriksson May 14 '18 at 05:29

2 Answers2

2

Change your admin_accountmanagement.js to

var btn_add_user = $('#btn_AddUser');

alert('Account management js loaded'); // this should show alert

$(document).on("click",btn_add_user,test);

function test(){
    alert("testing"); //doesn't work. no alert message
}

This method works because the binding is not dependent on "document ready" as document ready has already been fired when you loaded the parent page for the first time

Rohit Agre
  • 1,528
  • 1
  • 14
  • 25
0

@jordan i agree with @Magnus Eriksson as it is better to bind it on('event','selector','function') but make use of .off() before your .on() as you are playing with dynamic content which may cause multiple binding of the function. And if you are still not able to get the binding event to work you can try injecting the .js file in your page's head section after the load of your content like: $('head').append('<script src="admin_accountmanagement.js"></script>'). With your load() function in your js to bind the click event.

Or, your use the below code snippet:

function LoadContent()
{
 var url = 'view/admin_accountmanagement.php';
 var jssrc = 'js/admin_accountmanagement.js';
 div_content_container.html('');
 div_content_container.load(url);  
 if($('head').find('*[src="'+jssrc+'"]').length==0)
   {
   //the below approach have some consequences related to it as you will not be able to see the injected js in your developers tool's Sources(in chrome). 
   $('head').append('<script src="'+jssrc+'"></script>');
   }
}

and then on your .js will look like this:

var btn_add_user = null;
$(window).load(function(){
  alert("TEST"); 
  btn_add_user = $('#btn_AddUser');
  btn_add_user.off('click').on("click",test); //use .off('event') if load() is being called multiple times.
});

function test(){
   alert("testing"); 
}
vikscool
  • 1,293
  • 1
  • 10
  • 24