Sample Ajax GET/POST Request in Django
Sep 17, 2015 · 1 Min Read · 5 Likes · 8 Comments![Sample Ajax GET/POST Request in Django](/content/images/2020/03/ajax_hu9cc69366b1d70bd317fb436928e1c2cb_2208371_220x0_resize_q75_lanczos.jpg 220w,/content/images/2020/03/ajax_hu9cc69366b1d70bd317fb436928e1c2cb_2208371_440x0_resize_q75_lanczos.jpg 440w,/content/images/2020/03/ajax_hu9cc69366b1d70bd317fb436928e1c2cb_2208371_500x0_resize_q75_lanczos.jpg 500w,/content/images/2020/03/ajax_hu9cc69366b1d70bd317fb436928e1c2cb_2208371_600x0_resize_q75_lanczos.jpg 600w,/content/images/2020/03/ajax_hu9cc69366b1d70bd317fb436928e1c2cb_2208371_640x0_resize_q75_lanczos.jpg 640w,,/content/images/2020/03/ajax_hu9cc69366b1d70bd317fb436928e1c2cb_2208371_720x0_resize_q75_lanczos.jpg 720w,,/content/images/2020/03/ajax_hu9cc69366b1d70bd317fb436928e1c2cb_2208371_1024x0_resize_q75_lanczos.jpg 640w)
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.
Last updated: Jul 13, 2024
I won't spam you. Unsubscribe at any time.