Shiko
Shiko

Reputation: 149

How to push the data from Javascript to Django backend

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.

Upvotes: 1

Views: 683

Answers (1)

Daniel
Daniel

Reputation: 3527

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

  }
})

Upvotes: 1

Related Questions