Hacks by Ruddra

Sample Ajax GET/POST Request in Django

Let us make a test scenario here: A dropdown field which on change we are going to send a Get/Post request to Django and return response.

Let us start coding….

HTML code

<select id="select_dropdown">
  <option value="joshua">joshua</option>
  <option value="peter">peter</option>
  .... ....
</select>

Create an Ajax request

Let’s make an Ajax request after the change in the dropdown field.

$(document).ready(function(){

    $('#select_dropdown').change(function(){
    var e = document.getElementById("select_dropdown");
    var value = e.options[e.selectedIndex].value;

    $.ajax({
        url: "your-url",
        type: "post", // or "get"
        data: value,
        headers: {'X-CSRFToken': '{{ csrf_token }}'}, // for csrf token
        success: function(data) {

            alert(data.result);
        }});
    });
});

Handle AJAX request in django view

Here on change of a post request is called. Now let’s handle the view.

from django.http import JsonResponse
def post(request):
    if request.method == "POST": #os request.GET()
        get_value= request.body
        # Do your logic here coz you got data in `get_value`
        data = {}
        data['result'] = 'you made a request'
        return HttpResponse(json.dumps(data), content_type="application/json")

Thats all.

In conclusion

Above code should work both GET and POST methods. If you have any questions, please share in comments section below.


Topics: Django , Django View , Ajax , JS

Share Your Thoughts
M ↓   Markdown

Shivam Taneja
Monday, Aug 28, 2017

can you suggest me the process with the help of which we can change the drop down list with respect to other

Shivam Taneja
Monday, Aug 28, 2017

is this the complete process of ajax including views and templates

rardSkano
Monday, Dec 2, 2019

i am from Italy hello. Can you help me translate? /rardor

Ruddra
Tuesday, Dec 17, 2019

Hi Rardor, Unfortunately I don’t speak Italian. If you need any help to understand any part of this article, please share or ask in StackOverflow. Here is a link on how to use StackOverflow in Italian: https://simonecarletti.com/blog/2016/12/how-i-use-stackoverflow/

Bettyzox
Tuesday, Jan 14, 2020

If our expert life is driving us nut products, our personal life could be a living hell as well. A page with fewer hyperlinks is better than a page with a many links. You hold the power to your pleasure, not the person who hurt a person.

Ruddra
Sunday, Jan 19, 2020

Hahahaha !!!

Ruddra
Sunday, Jan 19, 2020

hahahaha!! I will try to keep that in mind next time.