I'm trying to submit a form without redirecting using AJAX. From the answers I saw the [best](new URLSearchParams(new FormData(form).entries());
) I found (I think) without using jQuery was:
const form = document.querySelector('form');
const data = Object.fromEntries(new FormData(form).entries());
I'm trying to apply this mechanism in my code, but for some reason my form
does not have information. I guess I'm calling the function before it gets recorded? But I'm not sure how to fix it.
My code (simplified):
HTML (using React and Reactstrap):
<Reactstrap.Form id="commentform" />
<Reactstrap.Input type="textarea" rows={4}></Reactstrap.Input>
</Reactstrap.Form>
...
<Reactstrap.Button onClick={()=>setTimeout(()=>{this.postComment()},500)}>Post</Reactstrap.Button>
JS (inside the same React class):
postComment=()=>{
let xhttp = new XMLHttpRequest();
const form = document.querySelector('#commentform'); //this gets the form properly
const data = Object.fromEntries(new FormData(form).entries()); //this doesn't return anything
xhttp.open("POST", '/postComment/', false); //don't mind the fact that this is synchronized, shouldn't matter
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //I in tutorials like W3S that this is required
xhttp.send('newcomment='+data);
}
Any help would be appreciated.
question from:
https://stackoverflow.com/questions/65945360/form-does-not-have-data-in-formdata-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…