function formValidation(){
var userid = document.getElementById(usuario);
var usermail = document.getElementById(correo);
var userpassword = document.getElementById(contrasena);
var userpasswordconfirm = document.getElementById(contrasena_conf)
if (userpassword == userpasswordconfirm){
var xhr = new XMLHttpRequest();
var data = new FormData();
data.append("Users", userid);
data.append("Mail", usermail);
data.append("pwd", userpassword);
xhr.open("POST", URL, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({
value: data
}));
else{
window.alert("Las contraseñas no coinciden");
userpassword.focus();
userpasswordconfirm.focus();
return false;
}
}
}
API server is receiving {"value": {}} and it is supposed to receive the user information. I don't know exactly what to put in setRequestHeader. Hope you can help me, thanks in advance
CodePudding user response:
Send the FormData object. Send only the FormData object. Do not try to be smarter than the browser about what the Content-Type of the FormData object is. Do not try to encode the data as JSON.
xhr.open("POST", URL, true);
// NO! xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);
Make sure the server side code that parses this request can handle multipart encoded form data.
var userid = document.getElementById(usuario);
This almost certainly wants to be:
var userid = document.getElementById("usuario").value;
Where you:
- use a string with the ID in it and not a variable (that probably has the element inside it and not the ID)
- get the value from the element instead of the whole element
All of your fields are plain text, so you could send JSON, but then you would need to construct a plain object and not a FormData object (and your server-side code would been to be prepared for JSON).
CodePudding user response:
function formValidation(){
var userid = document.getElementById("usuario").value;
var usermail = document.getElementById("correo").value;
var userpassword = document.getElementById("contrasena").value;
var userpasswordconfirm = document.getElementById("contrasena_conf").value;
if (userpassword != userpasswordconfirm){
window.alert("Las contraseñas no coinciden");
userpassword.focus();
userpasswordconfirm.focus();
return false;
}
else{
var xhr = new XMLHttpRequest();
var data = new FormData();
data.append("User", userid);
data.append("Mail", usermail);
data.append("Pwd", userpassword);
xhr.open("POST", URL, true);
xhr.send(data);
}
}
Thanks for helping this quickly, everything is working now. For those who asked, the backend code for the API:
@app.route("/route", methods=["POST"])
def add_new_user_data():
username = request.form.get("User")
usermail = request.form.get("Mail")
userpwd = request.form.get("Pwd")
print(username, usermail, userpwd)
if username is None:
return "The request is null", 400
else:
return "ok", 200