Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using POST in React without form?

Lets say I have this code here:

getInitialState:function(){
return { food: 'Chinese' }
},

restaurants:function(){
  return (<div><form method="post">
   <p>I like <span name="food">{this.state.food}</span> food</p>
   <button type="submit">Butane</button>
</form></div>);
},

My only experience with POST so far has been with forms and input fields. So I would like to know how to do this without, using more static content.

In the above example, I have content that isn't derived from an input field. I would like to put the state variable, in this case, Chinese, into a POST request.

Ideally, the button labeled butane submits the info from my state into my POST. And the span name is there to assign it a name for my back-end to read it from.

How would I re-arrange this code to enable use of the state variable in a POST context?

like image 546
Jason Chen Avatar asked Oct 23 '25 06:10

Jason Chen


1 Answers

You can add hidden input into form

<div>
  <form method="post">
     <p>I like <span name="food">{this.state.food}</span> food</p>
     <button type="submit">Butane</button>
     <!-- Hidden fields -->
     <input type="hidden" value={this.state.food}/>
  </form>
</div>

Update

Agree with @Rishat to use AJAX call.

For another situation which you want to do a normal POST request but don't want to add any input field to your form. You can use this solution: JavaScript post request like a form submit

like image 143
Jirat Ki Avatar answered Oct 24 '25 19:10

Jirat Ki