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?
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)
}