I am trying to use AJAX
with Django
but without jQuery
, almost I am successful in doing so but only urlencoded
data can be sent from AJAX to Django and unable to send data in JSON format, but I am able to get a response from Django
to AJAX
in JSON
format too.
I have tried a lot as you can see comments in these files:
senddata.html
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>Send AJAX data</title> </head> <body> <h2>Send AJAX data by using the button</h2> <button id="btn-submit" class="btn btn-outline-dark">SEND</button> <script> var sendbtn = document.getElementById('btn-submit') sendbtn.addEventListener('click', sendBtnHandler) function sendBtnHandler() { console.log('sendBtn is clicked') const xhr = new XMLHttpRequest() xhr.open('POST', 'http://localhost:8000/contact/send', true) // xhr.getResponseHeader("Content-type", "application/json"); // xhr.getResponseHeader("Content-type", "application/x-www-form-urlencoded"); // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xhr.onprogress = function () { console.log("on progress, wait a while until data is fetched") } xhr.onload = function () { console.log('success') console.log(this.responseText) } let params = `{"name":"mayur90","salary":"12213","age":"23"}` let b = 2 let d = 4 // let params = `a=${b}&c=${d}` xhr.send(params) // xhr.send(b) console.log(params) } </script> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script> --> </body> </html>
urls.py
from django.urls import path
from ajaxcontact import views
urlpatterns = [
path('', views.contact, name='contact'),
path('send', views.senddata, name='senddata'),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
@csrf_exempt
def senddata(request):
print(request.method)
# print(request.GET)
print('POST requests are', request.POST)
print(request.POST.get('name'))
if request.method == 'POST':
return JsonResponse('{"name":"a"}', safe=False)
return render(request, 'senddata.html')
Here, I use @csrf_exempt
to create the POST without the csrf token I am able to send data in urlencoded
but unable to send it in JSON
format
Any help will be appreciated
your urls should match with request url based on main domain. So change your urls.py file topath('/contact/send', views.senddata, name='senddata')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.