How to return a random number asynchronously using AJAX and Django

Viewed 29

As a beginner I apologize to being not particular as you wish, but hopefully you'll understand my problem.

What I am trying to achieve is simply returning a random value every 1.5 seconds without manually refreshing the browser. So far my code looks like this and it works, but I am convinced that my approach is kind of weird and around.

Is there any possibilty to have just one function that actually does the same as these two or any cleaner way to achieve this?

views.py:

def generate_random(request):
    return render(request, "form.html")

def generate_number(request):
    return HttpResponse(randint(0, 30))

my form.html is:

<head>  
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>    
</head>   
<body onload="getRandomInt();">

    <h2 id="result"></h2>

    <script>
        function getRandomInt() {
            setTimeout(function () {

              $.get("url", function(data, status){
                    $('#result').html(data);
                });

                getRandomInt();
            }, 1500)
            return false;
        }
    </script>  
</body>

and urls.py:

urlpatterns = [
    path('',generate_random),
    path('url',generate_number),
]
0 Answers
Related