Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, update part of the page

I'm trying to implement a simple code testing server. The client will submit their code on the webpage and we will run it with two test cases (which could take several minutes) and we'll post the results. The page will be simple with a submission form and an output box.

My problem is with updating the output box. I'm looking for the simplest way to implement the output box so that we show results as we run different test cases.

I tried googling for solutions and I found some like socket.io but my experience with ajax and socket.io or even js is very limited so I'm looking for the simplest way to do this.

like image 424
Kiarash Avatar asked Jan 15 '14 09:01

Kiarash


1 Answers

In case you are looking for code to auto-update a field in HTML here is the code which you could use. The setInterval in JavaScript schedules get_log view to be pulled every 1 second for result of get_log_from_disk method.

urls.py

    url(r'^get_log/$', 'myapp.views.get_log', name='get_log'),
    url(r'^submit/$', 'myapp.views.submit', name='submit'),

views.py

def submit(request):
    ## Handle POST
    ## Your code comes here
    return render(request, 'submit.html', {})

def get_log_from_disk():
    ## Your code comes here
    return "Test 1 OK; Test 2 OK"

def get_log(request):
    results = get_log_from_disk()
    return HttpResponse(results)

in submit.html add

<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>

<body>
[<div id="output_box"></div>]

<script>
$(document).ready(function() {
  $.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
  var my_refresh = setInterval(function() {
    $('#output_box').load('/get_log/');
  }, 1000); // the "1000"
});

</script>
</body>

You could modify "$('#output_box').load('/get_log/');" to test for status of request and when "204 No Content" is returned you can remove the function (clearInterval(my_refresh );)

see Stop setInterval call in JavaScript

Modify get_log view to return "204 No Content" when there is no more content to be sent.

Here I have uploaded working version

https://github.com/lukaszszajkowski/Django-jQuery-Example-update-part-of-page/tree/master

Some reading

Auto-refreshing div with jQuery - setTimeout or another method?

like image 157
fragles Avatar answered Sep 22 '22 05:09

fragles