How to render a field request without refreshing the page?

We’ll use ajax, with jQuery so be sure you have jQuery before you read.

first, you’ve to create an endpoint to GET, go to urls.py & add an endpoint say

path('/myserver/getID/', views.get_employee_name, name="whatever")

now, this calls get_employee_name right? Let’s now call it in JS without refreshing.

here’s the basic syntax ->

$.ajax({THIS IS A SIMPLE DICT})

ajax takes parameters

  • type which is the request type
  • url which is the request URL which we just made above (not the full url, you’re specifying the endpoint from where you’re located on the website so you just use /myserver/getID/)
  • it also takes data which is a dictionary with your posted data (yes a dictionary inside the bigger ajax dictionary
  • it CAN take success which is a function to call after getting the response with status 200 (success) and that success function can have the parameter response which is your response
  • it CAN take error which is a function that gets called after an error & takes error as argument

enough talking…

$.ajax({
    url: 'myserver/getID',
    type: 'GET',
    data: // don't specify this, we're not posting any data,
    success: function (response) {console.log(response.data)}, //this will be what returned from python
    error: function (error){console.log(error)}
})

this is a simple ajax request

NOTE, if you return a redirect from python & accept it from ajax, it won’t work, ajax can’t redirect, be sure to remember that because most of the time people ask why redirect('mylink') doesn’t work after I return it from ajax.

Another NOTE is the when dealing with post requests with ajax, you must include the csrf token which can be included by

csrfmiddlewaretoken: '{%csrf_token%}'

You can use Fetch API too if you want, or even normal XMLhttprequest.

Leave a Comment