Forums

Django Question regarding Ajax - how to update a template after success

If I have a button on a template which sends requests via Ajax, what is the gold-standard for updating the template? For example, if I have this Ajax function which is triggered on clicking a button....

$(document).ready(
    function() {
        $(".js-up").click(function(){

            //pass the username from index to the view, return the username from view, (silly - but ok for testing to see how it gets passed back and forth) then update the html? How?
             $.ajax({
                method: "POST",
                url: addItem,
                data:{'UserName' : user,  'csrfmiddlewaretoken': csrftoken},
                success: function(data){
                         //labels = data.labels;
                         //defaultData = data.default;
                         console.log(data.UserName) 
                     },
                error: function(error_data){
                          console.log("error");
                          console.log(error_data)
                    },
               });


        })

        $(".js-down").click(function(){
            console.log('down')
            //send information to database
        })
    }
);

which is routed to this view :

class AddItem(View):
     def post(self, request, *args, **kwargs):
        #print('called view')
        username =  request.POST.get('UserName')
        print(username)
        data = {
            'itemAdded': 'item was added', 'UserName' : username
        }

        return JsonResponse(data)

supposing my view did something to the back-end model, and I wanted to update the front-end. What are the best ways to do it? I see people who basically pass HTML via the response of the Ajax function.

Is that the best, or only way to do it - if not what are better, cleaner ways.

I apologise for the code presented -- I'm a noob

Oof, that's actually a really big question, and probably 90% of front-end web development is involved in the answer :-)

I'll try to give you a few pointers. Returning HTML isn't a common solution, and I'd avoid doing it myself. Returning JSON like you are currently doing is a popular solution, and I'd go with that -- it's what we do for our own site.

So the question is, how do you update the DOM (Document Object Model -- the browser's representation of what is on the page that it is showing) based on the response. Your options are:

  • Use JavaScript's built-in functions. This might be easy to get started with, but can get really complicated as your code gets larger. This looks like a good tutorial.
  • Use jQuery. This is a wrapper around JavaScript's built-in stuff that makes a lot of things easier, and it looks like you're already using it for your AJAX call. This was the most popular way to do things, but it's fallen out of favour over time, as newer ways to do things have appeared.
  • Use a front-end framework that handles it all for you. There's more setup and learning involved is using one, but it does pay off in the long run. The most popular ones are React, Vue.js, and Angular. We use React for PythonAnywhere, and it works pretty well. However, moving to one of those will probably involve moving logic out of Django templates and into templates managed by the JS framework.

Given that you're already using jQuery for your AJAX request, it's probably easiest to start by using that, but later on to go through a tutorial for one or more of the newer front-end frameworks to get a feel for how they make things easier -- then you can decide if you want to move over.

Thanks for the info. I feel like a kid in the candy-store. Vue vs React vs Angular.... Vue seems easiest? Probably for my simplistic stuff.

Just try.