I'm trying to get the data from a post form using vanilla JS asynchronously (avoiding refresh the page). I'm failing in some point because I can't access to the form's data.
template.html
<form method="POST" autocomplete="off" action="/index" id="mail_form_id">
{% csrf_token %}
<input type="email" name="mail_input" id="mail_input">
<button type="submit" onclick="send_mailform()" ></button>
...
views.py
...
if request.is_ajax:
print(request.POST['mail_input']) #This is not working
script.js
// I'm avoiding to refresh using this function
var form = document.getElementById("mail_form_id");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
function send_mailform(){
var http = new XMLHttpRequest();
http.open("POST", "/index", true);
http.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
var mail_input = document.getElementById('mail_input').value;
http.send(mail_input);
}
...
I've been searching and there are several solutions for django 1.X or using Jquery. I didnt put the getCookie function in scripts.js but it's working properly. I'm triying to avoid using Jquery. Thank you in advance!