NictheDEV
NictheDEV

Reputation: 187

Load new pages via Ajax without refreshing the whole nav bar Django

I'm new to Django and I'm building my own website. I have written a base.html page that contains the main body, CSS, js, fonts, and the navbar that all the pages of my site will have. The navbar is on another HTML file, navbar.html

Now, as soon as the CSS/js/fonts/navbar included in the base.html will be loaded on every page and won't change, is there a way with Ajax to load only the actual content of the page that change seamless without seeing the whole page refresh?

For instance, the part of the page that visually changes everytime is inside a <section class="home"></section> tag

Upvotes: 0

Views: 524

Answers (1)

Leeuwtje
Leeuwtje

Reputation: 345

When using JQuery, it is quite simple:

<script>
   function load_page(url) {
      $.ajax({
         url: url,
         success: function (data) {
            $('#nav_id').html('');
            data.nav_items.forEach(item => {
               $('#nav_id').append($('<div>').onclick(load_page(item.url)).text(item.title));
            }
         },
         error: function () {
            alert('Could not load data');
         }
      });
   }
</script>

And in your url you can define this as /nav/str:slug/ which leads to a view like this:

def nav_ajax(request, slug):
   if slug == 'a':
       return JsonResponse({
          'navitem1': {
              'title': 'A',
              'url': reverse('your_nav_url_name', kwargs={'slug':'a'}),
       },
       # other menu items
       )
   else:
      return JsonResponse({}) # default menu items

Upvotes: 1

Related Questions