-1

i just want to pass the selected id of the option via ajax request to django 2.1 but it always returns me some errors . i am new to django and web development so please help to solve this issue js code

document.addEventListener('DOMContentLoaded',()=>{
document.querySelector('#mainoption').onchange=()=>{
  const id=document.querySelector('#mainoption').value;
  const request=new XMLHttpRequest;

  request.open('GET','submain');
  request.send(id);
  alert("selected  "+id);
}

});

django code

def submain(request):
subid = request.GET.get('id')

print(subid)
return HttpResponse(subid)

django

javascript

frontend

the out put of subid is none why this happen

Community
  • 1
  • 1
codingKID
  • 33
  • 6

1 Answers1

0

The error message tells you that the submain view is not returning an HttpResponse object. You need to return an HttpResponse object.

from django.http import HttpResponse

def submain(request):
    subid = request.POST.get('id')
    return HttpResponse(subid)

Change your AJAX request to

document.addEventListener('DOMContentLoaded',()=>{
document.querySelector('#mainoption').onchange=()=>{
  const id=document.querySelector('#mainoption').value;
  const request=new XMLHttpRequest;

  request.open('POST','submain');
  request.send("id="+id);
  alert("selected  "+id);
}

  • yeah but the content inside subid is none – codingKID Jan 24 '19 at 05:48
  • The XMLHttpRequest.send() method ignores the body parameter if the request method is GET: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send. GET requests URL encode information, e.g. "http://example.com/submain/?id=1". You probably want to make a POST request to transmit data to the server – Jeremiah Simonsen Jan 24 '19 at 05:53
  • so what is the proper method to access the subid in django – codingKID Jan 24 '19 at 05:54
  • 1
    Send your AJAX request like the POST example here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send#Example_POST Then in your Django view, you can access it with ```request.POST.get('id')``` – Jeremiah Simonsen Jan 24 '19 at 05:57
  • This tutorial may be helpful: https://realpython.com/django-and-ajax-form-submissions/ For more complicated Django APIs, I highly recommend checking out Django REST Framework: https://www.django-rest-framework.org/ – Jeremiah Simonsen Jan 24 '19 at 06:01
  • You're welcome! If this helped, please accept my answer - I'm new and trying to earn some reputation. Thank you. – Jeremiah Simonsen Jan 24 '19 at 06:16