1

I am new to how javascript works, so I am trying to push the time spent on a page using Javascript to Django backend but I do not know how to do it, need some help to know how to do it.

Here is the javascript that is placed in the template:

$(document).ready(function() {
  var startDate = new Date();

  $(window).unload(function() {
      var endDate = new Date();
      $.ajax({ 
        type: POST,
        url: "/backendurl",
        data: {'timeSpent': endDate - startDate},
       
      })
   });
});

I am not sure what to do to push the data to Django backend using above Jquery POST.

2
  • Looks good so far, what issues are you having exactly? Commented Nov 7, 2020 at 1:46
  • how do i layout the data in Django backend? I am not sure how to view the data Commented Nov 7, 2020 at 1:49

1 Answer 1

1

urls.py:

urlpatterns = [
    ...
    path('backendurl', views.my_view_function, name='backendurl',
    ...
]

views.py:

def my_view_function(request):

    # unpack request:
    timeSpent = request.POST['timeSpent']

    # do some logic:
    ...

    # pack response:
    response = json.dumps({
        'status' : 'ok',
    })

    return HttpResponse(response)

script.js:

...
$.ajax({ 
  type: POST,
  url: "backendurl", // be mindful of url names
  data: {
    'timeSpent': endDate - startDate || 'none' // defaults to a string
  },
  success: function(response) {

    // unpack response:
    status = response.status

  }
})
Sign up to request clarification or add additional context in comments.

5 Comments

I followed the steps but i received MultiValueDictKeyError at /backendurl/ 'timeSpent'
That is likely because you are passing nothing into the ajax request, see my edited solution for how to set a default value.
could there be another reason for this error to appear as it is still showing?
the error is showing to due to the line in the views: timeSpent = request.POST['timeSpent'] , the data should appear in 127.0.0.1:8000/backendurl/ but it returns MultiValueDictKeyError at /backendurl/
This occurs because there is no parameter named 'timeSpent' in your ajax post request. If a field is null or undefined, ajax will not send it through in the post request. Hence you likely did not correctly set this field in your ajax post request and thus the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.