Skip to content
Advertisement

Form does not have data in FormData javascript

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.

Advertisement

Answer

From MDN docs

Note: FormData will only use input fields that use the name attribute.

Try naming the input element:

<Reactstrap.Input name="newcomment" type="textarea" rows={4}></Reactstrap.Input>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement