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:
JavaScript
x
3
1
const form = document.querySelector('form');
2
const data = Object.fromEntries(new FormData(form).entries());
3
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):
JavaScript
1
6
1
<Reactstrap.Form id="commentform" />
2
<Reactstrap.Input type="textarea" rows={4}></Reactstrap.Input>
3
</Reactstrap.Form>
4
5
<Reactstrap.Button onClick={()=>setTimeout(()=>{this.postComment()},500)}>Post</Reactstrap.Button>
6
JS (inside the same React class):
JavaScript
1
9
1
postComment=()=>{
2
let xhttp = new XMLHttpRequest();
3
const form = document.querySelector('#commentform'); //this gets the form properly
4
const data = Object.fromEntries(new FormData(form).entries()); //this doesn't return anything
5
xhttp.open("POST", '/postComment/', false); //don't mind the fact that this is synchronized, shouldn't matter
6
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //I in tutorials like W3S that this is required
7
xhttp.send('newcomment='+data);
8
}
9
Any help would be appreciated.
Advertisement
Answer
From MDN docs
Note: FormData will only use input fields that use the name attribute.
Try naming the input element:
JavaScript
1
2
1
<Reactstrap.Input name="newcomment" type="textarea" rows={4}></Reactstrap.Input>
2