0

I need to trigger a reactjs form submission from a button eventhandler to a fixed URL.

So far, I have seen SO examples (e.g. here) of form submission with a button of type submit

and with buttons of type button and onClick eventhandler, which seems to need a form with onSubmit eventhandler (see examples below)

With submit button inside form Working!

  render(){
  return(
     <div>
         <form id="form1" method="post" action="http://localhost:3000/">
             <label>
                 Name:
                 <input type="text" name="name" enctype='text/plain' value={this.state.data}  />
                 <button type="submit">Submit inside form</button>
             </label>
         </form>

With submit button and eventhandler Also working!

         <form id="form3" method="post" onSubmit={this.handleSubmit}>
         <label>
             Name:
             <input type="text" name="name" enctype='text/plain' value={this.state.data}  />
             <button type="submit">submit</button>
         </label>
        </form>
        <button
         onClick={ () =>
             document.getElementById('form3').dispatchEvent(new Event('submit'))}
        >
         This works
        </button>

I would just need to trigger a simple submit with an action from a button with an eventhandler, like in the not-working example below.

<form id="form4" method="post" action="http://localhost:3000/"  
onSubmit={this.doNothingLetActionDoTheJob}>
             <label>
                 Name:
                 <input type="text" name="name" enctype='text/plain' value={this.state.data}  />
                 <button type="submit">submit</button>
             </label>
         </form>
         <button
             onClick={ () =>
                 document.getElementById('form4').dispatchEvent(new Event('submit'))}
         >
             This does not work
         </button>

Is this possible? If yes, what am I doing wrong?

x y
  • 911
  • 9
  • 27
  • Why do you want to do that way? – Zohaib Ijaz May 15 '19 at 16:29
  • Because I don't want to write code for posting data. Which means to *require* packages and struggle with package version issues and all sorts of that stuff. – x y May 15 '19 at 16:32
  • You can use fetch and perform a AJAX call which would not require any additional libraries. – Ganesh chaitanya May 15 '19 at 16:44
  • @Ganeshchaitanya Do you by chance know, the best way to set the *HTML* response of the POST in the current window - which means: injecting the response into my active document. I am aware of security concerns! – x y May 16 '19 at 10:52
  • this.state = { data = ""; } componentDidMount(){ fetch('some_url') .then(response => response.json()) .then(data => this.setState({ data })); }
    {this.state.data}
    Try this
    – Ganesh chaitanya May 16 '19 at 11:38

0 Answers0