0

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!

VicenteC
  • 311
  • 7
  • 26
  • [Using XMLHttpRequest - Web APIs | Submitting forms and uploading files](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files) – Andreas Mar 19 '20 at 15:08
  • https://stackoverflow.com/questions/464040/how-are-post-and-get-variables-handled-in-python – azro Mar 19 '20 at 15:10
  • @azro I've used this solution, as you can see in the post, so the problem must be in the js file. How can I solve it? – VicenteC Mar 19 '20 at 15:15
  • Are you sure send_mailform is called ? Use a console.log into it, it can't help more – azro Mar 19 '20 at 15:19
  • You have to send key value pairs and not only the value – Andreas Mar 19 '20 at 15:21
  • @Andreas have I to send the cookie or what? send_mailform is being called – VicenteC Mar 19 '20 at 15:23

1 Answers1

-1

I don't think this is the best way to do this but it's possible to get the data sent using:

views.py

raw_data = request.body #Binary 
data = raw_data.decode("utf-8")
VicenteC
  • 311
  • 7
  • 26