1

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.

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.