javascriptphpload

how to load page into a div when click on a link without reload the window?


i have this html+php code :

<div class="categories_menu">               
<?php foreach($pt->categories as $key => $category) {
if (1) { ?>
<div class="items">
<a class="item_link" href="{{LINK videos/category/<?php echo $key?>}}" ><?php echo $category?></a>
</div>
<?php } }?>
</div>

<div id="load_cats" class="load_cats">  
 <!--load categories contents in this div -->         
</div>

the first code create a menu for categories by the php foreach methode.

this code : <a class="item_link" href="{{LINK videos/category/<?php echo $key?>}}" ><?php echo $category?></a> when click on it will open category page as a new page outside the current page.

i want to open category page inside the div id="load_cats" without reload/refresh the current page . the matter is open category inside the div instead of open the url in a full new window in browser.

this code can help but what is the code to load categories pages !!

$(".item_link").click(function() {
    $("load_cats").load("???");
});

i see on this site many topics speak about this , but because my code based on php foreach i cant use them .


Solution

  • You need this

    $(() => {
      $('.categories_menu').on('click','.item_link',function(e) {
        e.preventDefault(); // stop the link
        $('#load_cats').load(this.href);
      });
    });
    

    Assuming this generated html, and that /videos/category/key1 will load an HTML partial

    <div class="categories_menu">               
      <div class="items">
        <a class="item_link" href="/videos/category/key1" >key1</a>
      </div>
      <div class="items">
        <a class="item_link" href="/videos/category/key1" >key1</a>
      </div>
      <div class="items">
        <a class="item_link" href="/videos/category/key1" >key1</a>
      </div>
    </div>
    
    <div id="load_cats" class="load_cats">  
     <!--load categories contents in this div -->         
    </div>