XiLab XiLab - 6 months ago 13
Javascript Question

Properly Reload div via Ajax - Script disappears

I have my header.php containing a button which triggers the sidebar menu to appear. Button and sidebar are visible only for logged in users. At the end of this block there is a little piece of code that adds the class "active" to my sidebar for making it visible. It's something like:

<div id="header">
<!-- if is_user_logged_in -->
<a id="menu-toggle" href="#" type="button">
<i class="sprite-t-toggle-side"></i>
</a>
<!-- sidebar menu-->
<div id="sidebar-wrapper"><!-- menu content --></div>
<script>
var $menu = $("#sidebar-wrapper");
$("#menu-toggle").on("click", function(e) {
e.preventDefault(),
$menu.toggleClass("active");
});
</script>
</div>


Now, I make my users login via AJAX and once they're logged I just refresh my header block for displaying button and sidebar. I use this line of code to do so in my AJAX success:

success: function(data){
if (data.loggedin == true){
$("#header").load(location.href + " #header");
}
}


Until here everything is fine, users are logged and button is displayed but when I click on it nothing happens. Sidebar won't appear and If I look at the code my little function, at the end of header, is missing. Otherwise, If I reload the whole page it works.
What's happening? What am I doing wrong?

Answer

Why reload the entire header. Why not just grab the logged in part of it

I think problem is that you are reloading the entire #header you need to just reload part of it.


$("#header").load(location.href + " #header"); <- this will replace all html in the #header

<div id="header">
<div id="loadajax"></div> <!-- Put loaded ajax in here --->
<!-- if is_user_logged_in -->
<a id="menu-toggle" href="#" type="button">
  <i class="sprite-t-toggle-side"></i>
</a>
<!-- sidebar menu-->
<div id="sidebar-wrapper"><!-- menu content --></div>
<script>
function runMenu() {
   var $menu = $("#sidebar-wrapper");
   $("#menu-toggle").on("click", function(e) {
     e.preventDefault(), 
     $menu.toggleClass("active");
   });
}
runMenu();
</script>
</div>

success: function(data){
   if (data.loggedin == true){
      $("#loadajax").load(location.href + " #header");
      runMenu();
  }
}
Comments