Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
django form.is_valid returns false when while using XMLHttpRequest

since bootstrap 5 no longer ships with jquery and recommends using the vanilla javascript XMLHttpRequest() to make dynamic requests that is what I am trying to do in django. All the other examples of doing this use the traditional .$ajax. I have a basic javascript function:

function sendPhoneVerification(_phone) {
    var http = new XMLHttpRequest();
    const params = {
            phone: _phone
    }
    http.open('POST', '/approvephone/', true)
    http.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
    http.setRequestHeader('Content-type', 'application/json')
    http.setRequestHeader('phone', _phone)
    http.send(JSON.stringify(params))
    http.onload = function() {
        alert(http.responseText)
    }
}

The CSRF middlware token is working fine, but the in the view, the form.is_valid() returns false and the error is that required field "phone" is missing. I can't tell how I am supposed to provide that value. The form being tested against is a simple form with one field

class AddPhoneForm(forms.Form):
    phone = PhoneNumberField()

relevant part of the view

@csrf_protect
@login_required
def approvephone(request):
    if request.method == 'POST':
        form = AddPhoneForm(request.POST)
        if form.is_valid()  #returns false and error is missing field "phone"

Any idea how I can correctly provide the phone fields in the POST response to make django happy?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

ok I feel stupid, but in django you need to send 'Content-type', 'application/x-www-form-urlencoded' as described here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

function sendPhoneVerification(_phone) {
    alert("Hello! I am an alert box!!" + _phone);
    var http = new XMLHttpRequest();
    http.open('POST', '/approvephone/', true)
    http.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    http.send("phone="+_phone)

    http.onload = function() {
        alert(http.responseText)
    }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!