How to get a form to disapear upon submission in React - reactjs

This is a 'contact us' form on a website.
I want all the cells of the form to disappear after the user clicks the 'submit' button upon 'success'. In other words, I wont the form to no longer be rendered if the submission is a success. Since this is React, I wouldn't want the page to do an old fashioned reload, just go away upon the condition.
The way it works now upon submission only the button disappears if the submission is a success and nothing disappears if the submission is a failure, which can remain the same.
This is a form that uses XML with a Google Apps Script to send the user's entered form data upon submission. This all works fine and there is something within the 'status' state working with the onSubmit action that is making the Conditional Rendering not so straight forward.
IF YOU WOULD LIKE TO TEST THIS IN REACT TO WORK IT OUT
Since I don't want to put my email code there you should make the 'else' condition that sets 'status' to say 'SUCCESS' near the bottom at 'this.setState({ status: "ERROR" });' so the if/ else in the email sending function (at the bottom) will render the form as if the data went through and the email was sent. My suggestion.
The code below is how the component works normally but my attempt to solve this problem was to store all the cells above as a variable and 'return' it if 'status' was > 0. Because status is "" before the button is pressed. This just caused the whole page to reload, re-rendering the whole DOM and not sending the email.
import React from 'react';
export default class MyForm extends React.Component {
constructor(props) {
super(props);
this.submitForm = this.submitForm.bind(this);
this.state = {
status: ""
};
}
render() {
const { status } = this.state;
return (
<form
onSubmit={this.submitForm}
action="https://script.google.com/macros/s/000000AKfycbz000000000C0/exec"
method="POST"
>
<div className="row_10" style={{"margin-top": "30px"}}>
<div className="col-25">
</div>
<div className="col-75">
<input type="text" id="name" name="Name" placeholder="Name:"/>
</div>
</div>
<div className="row_10">
<div className="col-25">
</div>
<div className="col-75">
<input type="text" id="Phone" name="Phone" placeholder="Phone:"/>
</div>
</div>
<div className="row_10">
<div className="col-25">
</div>
<div className="col-75">
<input type="text" id="Email" name="Email" placeholder="Email:"/>
</div>
</div>
<div className="row_10">
<div className="col-25">
</div>
</div>
<div className="row_10">
<div className="col-25">
</div>
<div className="row_10">
<textarea className="col-75_T" id="subject" name="subject" placeholder="How can we help you?" style={{"height": "190px"}}></textarea>
</div>
</div>
<div className="subm_button">
<div className="col-25">
</div>
</div>
{status === "SUCCESS" ? <p>Thank you! We will talk to you soon!</p> :<input onClick="fbq('track', 'Contact');" type="submit" value="Submit"/>}
{status === "ERROR" && <p>Ooops! There was an error.</p>}
</form>
);
}
submitForm(ev) {
ev.preventDefault();
const form = ev.target;
const data = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = () => {
if (xhr.readyState !== XMLHttpRequest.DONE) return;
if (xhr.status === 200) {
form.reset();
this.setState({ status: "SUCCESS" });
} else {
this.setState({ status: "ERROR" });
}
};
xhr.send(data);
}
}

Apply the same logic you have with your message to your form
renderForm() {
return (
<form
onSubmit={this.submitForm}
action="https://script.google.com/macros/s/000000AKfycbz000000000C0/exec"
method="POST"
>
<div className="row_10" style={{"margin-top": "30px"}}>
<div className="col-25">
</div>
<div className="col-75">
<input type="text" id="name" name="Name" placeholder="Name:"/>
</div>
</div>
<div className="row_10">
<div className="col-25">
</div>
<div className="col-75">
<input type="text" id="Phone" name="Phone" placeholder="Phone:"/>
</div>
</div>
<div className="row_10">
<div className="col-25">
</div>
<div className="col-75">
<input type="text" id="Email" name="Email" placeholder="Email:"/>
</div>
</div>
<div className="row_10">
<div className="col-25">
</div>
</div>
<div className="row_10">
<div className="col-25">
</div>
<div className="row_10">
<textarea className="col-75_T" id="subject" name="subject" placeholder="How can we help you?" style={{"height": "190px"}}></textarea>
</div>
</div>
<div className="subm_button">
<div className="col-25">
<input onClick="fbq('track', 'Contact');" type="submit" value="Submit"/>
</div>
</div>
</form>
);
}
render() {
const { status } = this.state;
const submitted = status === "SUCCESS";
return (
<>
{!submitted && this.renderForm()}
{submitted && <p>Thank you! We will talk to you soon!</p>}
{status === "ERROR" && <p>Ooops! There was an error.</p>}
</>
);
}

Related

ReactJS Email form validation : Could not move to the next page

I am working on a project where if the login detail is valid, we move to the next page ("/home"). But in my case, while it works perfectly good when the email is invalid, it does not go the expected page when the email is valid. Instead, the page only reloads. Although I have done the necessary in the onSubmit function. Please help
class Test extends React.Component {
constructor(){
super();
this.state = emailState;
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.setState({
email : e.target.value
});
}
emailValidation(){
const regex = /^(([^<>()[\]\.,;:\s#\"]+(\.[^<>()[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if(!this.state.email || regex.test(this.state.email) === false){
this.setState({
error: "Email is not valid"
});
return false;
}
return true;
}
onSubmit(){
if(this.emailValidation()){
console.log(this.state);
this.props.history.push('/home');
}
}
render(){
return (
<div className="login-cot bg-danger" id="layoutAuthentication">
<div id="layoutAuthentication_content">
<main>
<div className="container ">
<div className="row justify-content-center ">
<div className="col-lg-5 ">
<div className="card shadow-lg border-0 rounded-lg mt-5 bg-secondary">
<center><h1 className="bg-warning" style={{padding:"10px",}}><b><BsBugFill /><BsTools /> <BsColumns /> BFP</b></h1></center>
<div className="card-header"><h3 className="text-center my-1"><b>Login</b></h3></div>
<div className="card-body">
<form>
<div className="form-floating mb-3">
<input className="form-control" id="email" type="email"
placeholder="name#example.com"
value={this.state.email}
onChange={this.onChange}
/>
<label for="inputEmail">Email address</label>
<span className="text-danger">{this.state.error}</span>
</div>
<button type ="submit" className="btn btn-success" onClick={()=>this.onSubmit()}>Login</button>
</form>
</div>
<div className="card-footer text-center py-3">
<div className="small"><Link className="text-light" to="/signup">Need an account? Sign up!</Link></div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
)
}
}
Try to use withRouter() function with react , which helps to access the history parameter.
For e.g in your case : export default withRouter(Test);

React redirecting to ? parameter while submitting request instead of Rest api

Hitting submit from http://localhost:3000/newReport.
i have three fields treeselectdropdown, a textbox and a number field. i am setting days in state.
It redirect to http://localhost:3000/newReport?days=10 (if i give no of days as 10).
**import React from 'react';
import TestDropdownTreeSelect from './DropdownTreeSelect';
import Select from 'react-select';
class NewReport extends React.Component{
constructor() {
super();
this.state = {
days:null
};
this.getResults = this.getResults.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange({ target }) {
this.setState({
days: target.value
});
}
getResults() {
if(this.state.days!=null || this.state.days!=0)
alert(this.state.days);
fetch('*********************/************/getReportData?libraryName=R1_CONTENT_en_IN')
.then(res => res.text())
.then(text => {
console.log('R4_CONTENT_en_US----------------')
console.log(text);
console.log('R4_CONTENT_en_US----------------')
}).catch(err => {
console.log("ERROR: " + err);
})
}
render(){
return (
<div>
<form required>
<div class="label">
<b>New Report</b>
</div>
<br></br>
<div className="container">
<div class="row">
<div class="col-md-2">
<div class="labelNameLib">
<b>Library</b>
</div></div>
<div class="col-md-4">
<TestDropdownTreeSelect />
</div>
</div>
</div>
<div className="container">
<div className="row">
<div className="col-md-2">
<div class="labelName">
<b>Author</b>
</div>
</div>
<div className="col-md-2">
{/* <Select options={Authors}></Select> */}
<input type="text" ></input>
</div>
<div className="col-md-2"></div>
</div>
</div>
<br></br>
<div className="container">
<div className="row">
<div className="col-md-2">
<div class="labelName">
<b>Expiry Date in Next</b>
</div> </div>
<div className="col-md-2">
<input type="number" required
title="Enter number from 1 to 365"
value={ this.state.days } name="days"
onChange={ this.handleChange }
pattern="[0-9]{1,3}" min="1" max ="365"></input>
</div>
<div className="col-md-1"><b>Days</b></div>
</div>
</div>
<br></br>
<div>
<button type="submit" class="runReport"
onClick={this.getResults}
style={{ backgroundColor: '#FFD700', marginLeft: '15%' }}>Run Report</button>
</div>
<div>
</div>
</form>
</div>
);
}
}**
I am not getting rest api result in console. Why it is redirecting to ?days=10.
i am using fetch for hitting rest api requests
This is the expected behaviour with a form. You test the example on the page, the page is reloaded. To prevent this with JavaScript you have to use event.preventDefault(). Here is the snippet updated:
class NewReport extends React.Component{
getResults(event) {
event.preventDefault();
// ...
}
}

How to set value of an input from Redux store, but then still be able to write in that input and update value?

My input is also like a searchbox: I want to be able to search for names on the input but then I want to be able to click a name from the dropdown search results and set the input with that value. I then want to be able to search again if I want to change that value.
Tried using DefaultValue and uncontrolled components, but neither worked. Not sure if I used them right though.
class PublishTest extends Component {
constructor() {
super();
this.state = {
showRows: false,
numberOfRows: ["row"],
search: "",
searchResults: [],
insightListActive: false,
insightTagsActive: false
};
this.hideOrShowRows = this.hideOrShowRows.bind(this);
this.addNewRow = this.addNewRow.bind(this);
this.searchAllUsers = this.searchAllUsers.bind(this);
this.onChangeInsight = this.onChangeInsight.bind(this);
this.clearInput = this.clearInput.bind(this);
this.clearInsightList = this.clearInsightList.bind(this);
this.searchInsightTags = this.searchInsightTags.bind(this);
this.clearTagList = this.clearTagList.bind(this);
}
componentDidMount() {
this.props.getLoginCredential();
this.props.getAllRoles();
}
hideOrShowRows() {
this.setState({
showRows: !this.state.showRows
});
}
addNewRow() {
this.setState({
numberOfRows: [...this.state.numberOfRows, "row"]
});
}
searchAllUsers(e) {
this.setState({
search: e.target.value
});
const searchOption = this.state.search;
fetch("http://localhost:3500/soiapi/", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
data: [
{
name: "searchUser",
urlparameter: { search: searchOption, appId: "1" },
parameter: ""
}
]
})
})
.then(res => res.json())
.then(data => {
this.setState({
searchResults: data[0]
});
});
}
onChangeInsight = e => {
this.props.insightOnChangeValue(e.target.value);
this.props.searchInsights(e.target.value);
this.setState({
insightListActive: true
});
};
clearInput() {
this.setState({
search: "",
searchResults: []
});
}
clearInsightList() {
this.setState({
insightListActive: false
});
}
searchInsightTags(e) {
this.props.getInsightTags(e.target.value);
this.setState({
insightTagsActive: true
});
}
clearTagList() {
this.setState({
insightTagsActive: false
});
}
render() {
const { searchResults } = this.state;
let rows;
let button;
let icon;
if (this.state.showRows) {
rows = this.state.numberOfRows.map((row, i) => (
<div>
<Row index={i} />
</div>
));
button = (
<button
onClick={this.addNewRow}
className="Button--secondary float-right"
>
Add Row
</button>
);
icon = (
<i aria-hidden="true" className="Icon Icon--minus-small iconFont"></i>
);
} else if (!this.state.showRows) {
icon = (
<i aria-hidden="true" className="Icon Icon--plus-small iconFont"></i>
);
}
if (this.props.user.userDTO) {
const { userDTO } = this.props.user;
const insightSearchResults = this.props.insightReducerValue
.insightList[0];
return (
<div style={{ padding: "5px" }} className="publish-container">
<h4 className="publish-h4">Publish Insights</h4>
<h6 className="publish-h6">Insight Details</h6>
<hr className="line-style" />
<section id="publish-section-1">
<div class="Grid">
<div class="Col Col--3">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label insight-label">
Insight Name <span className="asterisk">*</span>:
</label>
<div id="insight-container">
<input
type="text"
placeholder="Insight Name"
onChange={this.onChangeInsight}
onFocus={this.clearInsightList}
onBlur={this.clearInsightList}
className="Form-input"
value={this.props.insightReducerValue.insightValue}
/>
{this.state.insightListActive ? (
<InsightList insights={insightSearchResults} />
) : null}
</div>
</div>
</div>
</div>
<div class="Col Col--3">
<div class="grid-block">
<div class="Form-group publish-insights-input">
<label class="Form-label">
Insight Source <span className="asterisk">*</span>:
</label>
<select
id="insight-source"
role="combobox"
class="Form-input"
>
<option
disabled="disabled"
selected="selected"
aria-disabled="true"
>
Choose one
</option>
<option>Tableau</option>
<option>Qlik</option>
<option>D3JS</option>
<option>CXI</option>
</select>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-2">
<div class="Grid">
<div class="Col Col--6">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label class="Form-label">
URL <span className="asterisk">*</span>:
</label>
<input type="text" placeholder="URL" class="Form-input" />
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-3">
<div class="Grid">
<div class="Col Col--6">
<div class="grid-block">
<div className="publish-insights-input">
<label class="Form-label">
Description <span className="asterisk">*</span>:
</label>
<textarea
placeholder="Description"
class="Form-input"
></textarea>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-4">
<div class="Grid">
<div class="Col Col--3">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label third-div-p">
POC Name <span className="asterisk">*</span>:
</label>
<input
type="text"
placeholder="Name"
className="Form-input"
value={`${userDTO.firstName} ${userDTO.lastName}`}
/>
</div>
</div>
</div>
<div class="Col Col--3">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label third-div-p">
Group Distro (E-mail Address)
<span className="asterisk">*</span>:
</label>
<input
type="text"
placeholder="Email"
class="Form-input"
value={userDTO.emailAddress}
/>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-5">
<div class="Grid">
<div class="Col Col--6">
<div class="grid-block">
<div class="Form-group publish-insights-input">
<div class="Form-checkbox is-restricted">
<input
id="restricted"
name="checkboxDefault"
type="checkbox"
/>
<label for="restricted">Is Restricted</label>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-6">
<div class="Grid">
<div class="Col Col--2">
<div class="grid-block">
<div id="tree-section">
<label id="category-label" className="Form-label">
Category <span className="asterisk">*</span>
</label>
<div id="tree-container">
<PublishInsightsTree />
</div>
</div>
</div>
</div>
<div class="Col Col--4">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label third-div-p">
Add Insight Tags <span className="asterisk">*</span>:
</label>
<input
type="text"
onChange={e => this.searchInsightTags(e)}
onFocus={this.clearTagList}
onBlur={this.clearTagList}
placeholder="Write some insight tags"
className="Form-input"
/>
</div>
{
this.state.insightTagsActive ?
<div>
{
this.props.insightTags ?
<InsightTags tags={this.props.insightTags[0]} />
: null
}
</div>
: null
}
</div>
<div class="grid-block">
<div class="Grid">
<div class="Col Col--7 img-url-input">
<div class="grid-block">
<div
id="file-div"
class="Form-group publish-insights-input"
>
<label class="Form-label">
Image URL <span className="asterisk">*</span>:
</label>
<input
type="text"
placeholder="Insight Name"
class="Form-input"
/>
</div>
</div>
</div>
<div class="Col Col--5">
<div class="grid-block">
<button class="Button--secondary upload-image-button">
Upload Image
</button>
</div>
</div>
<div class="Col Col--7 url-description">
<div class="grid-block">
<p>
Please copy paste the generated URL after uploading
image file.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-7">
<h6 className="publish-h6">Role Details</h6>
<hr className="line-style" />
</section>
<section id="publish-section-8">
<div class="Grid">
<div class="Col Col--2">
<div class="grid-block">
<label id="roles-label" className="Form-label">
Assign to Role <span className="asterisk">*</span>
</label>
<div id="all-roles">
{this.props.listOfRoles ? (
<ListOfRoles roles={this.props.listOfRoles} />
) : null}
</div>
</div>
</div>
<div class="Col Col--4">
<div class="grid-block assign-user-div">
<label className="Form-label label-spacing">
Assign to Individual User:
</label>
<div className="Form-group">
<textarea
onChange={this.searchAllUsers}
type="text"
placeholder="Look up by EID/Name"
onFocus={this.clearInput}
onBlur={this.clearInput}
className="Form-input assign-user-textarea"
value={this.state.search}
></textarea>
{searchResults.length > 0 ? (
<div id="user-list">
{searchResults ? (
<UserList searchResults={this.state.searchResults} />
) : null}
</div>
) : null}
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-9">
<h6 className="publish-h6 metadata-heading" onClick={this.hideOrShowRows}>
<span id="metadata-icon">{icon}</span>
Metadata Info
</h6>
<hr className="line-style color" />
</section>
<section id="publish-section-10">
<div class="Grid">
<div class="Col Col--12 add-row-col">
<div class="grid-block">{button}</div>
</div>
</div>
{rows}
</section>
</div>
);
} else {
return null;
}
}
}
const mapStateToProps = state => ({
user: state.LoginReducer.loginInfo,
searchUser: state.LoginReducer.searchUser,
insightReducerValue: state.SideDrawerReducer,
listOfRoles: state.LoginReducer.listOfRoles,
insightTags: state.SideDrawerReducer.insightTags
});
export default connect(
mapStateToProps,
{
getLoginCredential,
searchUser,
insightOnChangeValue,
searchInsights,
getAllRoles,
getInsightTags
}
)(PublishTest);
This is the part of the code I need help with:
<input
type="text"
placeholder="Insight Name"
onChange={this.onChangeInsight}
onFocus={this.clearInsightList}
onBlur={this.clearInsightList}
className="Form-input"
value={this.props.insightReducerValue.insightValue}
/>
{this.state.insightListActive ? (
<InsightList insights={insightSearchResults} />
) : null}
Since your code is a little messy, I made a sandbox that fetches some data from a dummy API, stores that data to our local component state. We have a text field where we can type in usernames and a list of matching usernames will appear as a dummy drop, clicking any one of those usernames will set the value in the text field. It's pretty straight forward will give you an idea on how to get started.
EDIT:
Sandbox Link: https://codesandbox.io/s/eloquent-pascal-pf3hd?fontsize=14
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
input: "",
users: [],
dropdown: []
};
async componentDidMount() {
let users = await fetch("https://jsonplaceholder.typicode.com/users");
users = await users.json();
this.setState({ users });
}
handleChange = e => {
this.setState({ input: e.target.value }, () => {
let results = this.state.users.filter(user => {
return user.username.indexOf(this.state.input) > -1;
});
this.setState({ dropdown: results });
});
};
handleSelect = username => e => {
this.setState({ input: username }, () => this.setState({ dropdown: [] }));
};
render() {
return (
<div className="App">
<h1>Search</h1>
<input
type="text"
name="input"
onChange={this.handleChange}
value={this.state.input}
/>
{this.state.dropdown.map(d => (
<h3 onClick={this.handleSelect(d.username)} key={d.id}>
{d.username}
</h3>
))}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Could you start off by loading all possible search results into state or props (e.g. under this.props.searchResults)? Then you could try using the datalist tag. Not quite sure if this was what you were going for, but it looked like something like that could work for you.
<input type="text"
defaultValue={this.props.insightReducerValue.insightValue}
list="inputOptions"
onChange={(e) => console.log("Current input field value: ", e.target.value)} />
<datalist id="inputOptions">
{this.props.searchResults.map((item, key) =>
<option key={key} value={item} />
)}
</datalist>
P.S. Check the supported browsers list under the link.

How to fix redux form validation error in edit record

When I go the edit form page and when I submit the form without doing any changes it shows me "required" error in all field.
check the error in this image.
Edit page image
Here is my edit page code. It's not all the code but some code.
const renderField = ({
defaultValue,
input,
meta: { touched, error },
...others
}) => {
const { value, ...newVal } = input;
return (
<div>
<div>
<input
{...newVal}
{...others}
defaultValue={value ? value : defaultValue}
/>
{touched && (error && <span style={{ color: "red" }}>{error}</span>)}
</div>
</div>
);
};
class Edit extends Component {
render() {
const { user } = this.state;
const { handleSubmit, submitting } = this.props;
return (
<div className="container">
<div className="row">
<section className="section section-register">
<div className="valign-wrapper row register-box">
<div className="col card hoverable s10 pull-s1 m6 pull-m3 l0 pull-l0">
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<div className="card-content">
<h5 className="grey-text text-darken-3">Sign Up</h5>
<div className="row">
<div className="input-field col s12">
<Field
placeholder="First Name"
id="firstName"
name="firstName"
type="text"
onChange={this.handleChange}
defaultValue={user.firstName}
component={renderField}
validate={required}
/>
</div>
</div>
</div>
<div className="card-action right-align">
<button
className="btn waves-effect waves-light"
type="submit"
name="submit"
disabled={submitting}
>
Submit
</button>
</div>
</form>
</div>
</div>
</section>
</div>
</div>
);
}
}
Can anyone figure it out what's problem is? I couldn't find any issue.

Showing input value in the url link (ReactJs Laravel)

I created laravel project with the reactjs framework and I'm new for this framework. I have problem and why It happens every time i submit the form.
Goal: users can register through online
Problem:
Why it happens when i submit the button the input value of user shown in the url link?
The data that I input is not inserted to the database.
Code:
constructor() {
super();
this.state = {
f_name:'',
l_name:'',
m_name:'',
email:'',
home_num:'',
contact_num:'',
Job_name:[],
employ_status:'',
employ_relocate:'',
employ_start_date:'',
employ_file:''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handle_fname = this.handle_fname.bind(this);
this.handle_lname = this.handle_lname.bind(this);
this.handle_mname = this.handle_mname.bind(this);
this.handle_email = this.handle_email.bind(this);
this.handle_homenum = this.handle_homenum.bind(this);
this.handle_contactnum = this.handle_contactnum.bind(this);
this.handle_employ_status = this.handle_employ_status.bind(this);
this.handle_employ_relocate = this.handle_employ_relocate.bind(this);
this.handle_employ_start_date = this.handle_employ_start_date.bind(this);
this.handle_employ_file = this.handle_employ_file.bind(this);
}
componentDidMount() {
const id = this.props.match.params.id;
axios.get('/api/online_application_job_title/' +id).then(response => {
this.setState({
Job_name:response.data
})
})
}
handleSubmit(e)
{
const data = {
firstname: this.state.f_name,
lastname : this.state.l_name,
middlename : this.state.m_name,
email : this.state.email,
home_number : this.state.home_num,
contact_num : this.state.contact_num,
job : this.state.Job_name[0].position_name,
employ_status : this.state.employ_status,
employ_relocate : this.state.employ_relocate,
employ_start_date : this.state.employ_start_date,
employ_file : this.state.employ_file
}
axios.post('/api/save_application',data).then(response => {
console.log(response);
}).catch(error => console.log(error));
}
handle_fname(e)
{
this.setState({
f_name:e.target.value,
})
}
handle_lname(e){
this.setState({
l_name:e.target.value,
})
}
handle_mname(e){
this.setState({
m_name:e.target.value,
})
}
handle_email(e){
this.setState({
email:e.target.value,
})
}
handle_homenum(e){
this.setState({
home_num:e.target.value
})
}
handle_contactnum(e){
this.setState({
contact_num:e.target.value
})
}
handle_employ_status(e){
this.setState({
employ_status:e.target.value
});
}
handle_employ_relocate(e){
this.setState({
employ_relocate:e.target.value,
})
}
handle_employ_start_date(e){
this.setState({
employ_start_date:e.target.value,
})
}
handle_employ_file(e){
this.setState({
employ_file: e.target.files[0].extension
})
}
renderName() {
return (
this.state.Job_name.map(name => (
<input placeholder="" value={name.position_name} type="text" className="form-control"/>
))
)
}
render() {
return (
<div>
<div className="header">
<div className="jumbotron">
<h1>Online Application</h1>
</div>
</div>
<form onSubmit={this.handleSubmit}>
<div className="container">
<h5><b>Personal Info</b></h5>
<br/>
<div className="row">
<div className="col-md-6">
<input
placeholder="First Name*"
value={this.state.f_name}
onChange={this.handle_fname}
className="form-control"/>
</div>
<div className="col-md-6">
<input
placeholder="Last Name*"
value={this.state.l_name}
onChange={this.handle_lname}
className="form-control"/>
</div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<input
placeholder="Middle Name*"
value={this.state.m_name}
onChange={this.handle_mname}
className="form-control"/>
</div>
<div className="col-md-6">
<input
placeholder="Email Address*"
type="email"
value={this.state.email}
onChange={this.handle_email}
className="form-control"/>
</div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<input
placeholder="Home Number*"
type="number"
value={this.state.home_num}
onChange={this.handle_homenum}
className="form-control"/>
</div>
<div className="col-md-6">
<input
placeholder="Contact Number*"
type="number"
value={this.state.contact_num}
onChange={this.handle_contactnum}
className="form-control"/>
</div>
</div>
<br/><br/>
<h5><b>Employment Application</b></h5>
<br/>
<div className="row">
<div className="col-md-6">
<p>Position Applying For</p>
{this.renderName()}
</div>
<div className="col-md-6">
</div>
</div>
<br/><br/>
<div className="row">
<div className="col-md-6">
<p>1. What is your current employment status?</p>
<div className="form-check-inline">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Unemployed"/>Unemployed
</label>
</div>
<div className="form-check-inline">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Employed"/>Employed
</label>
</div>
<div className="form-check-inline disabled">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Self-Employed"/>Self-Employed
</label>
</div>
<div className="form-check-inline disabled">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Student"/>Student
</label>
</div>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<p>2. Are you willing to relocate?</p>
<div className="form-check-inline">
<label className="form-check-label">
<input type="radio"
name="relocate"
onChange={this.handle_employ_relocate}
className="form-check-input"
value="Yes"/>Yes
</label>
</div>
<div className="form-check-inline">
<label className="form-check-label">
<input type="radio"
name="relocate"
onChange={this.handle_employ_relocate}
className="form-check-input"
value="No"/>No
</label>
</div>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<p>3. When is your available start date?</p>
<input
name="startdate"
type="date"
onChange={this.handle_employ_start_date}
value={this.state.employ_start_date}
required=""
className="form-control"/>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<p>4. Kindly attach a copy of your resume (PDF,docx files only).</p>
<div className="custom-file">
<input
type="file"
name="file"
accept="application/msword,application/pdf"
onChange={this.handle_employ_file}
className="custom-file-input"
id="inputGroupFile04"/>
<label className="custom-file-label" htmlFor="inputGroupFile04">Choose file</label>
</div>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<input
className="btn btn-outline-primary btn-large form-control col-md-5"
type="submit"
value="Send Application"/>
</div>
<div className="col-md-6"></div>
</div>
</div>
</form>
</div>
)
}
Controller:
public function save_application(Request $request)
{
$firstname = $request->get('firstname');
$lastname = $request->get('lastname');
$middlename = $request->get('middlename');
$email = $request->get('email');
$home_number = $request->get('home_number');
$contact_num = $request->get('contact_num');
$job = $request->get('job');
$employ_status = $request->get('employ_status');
$employ_relocate = $request->get('employ_relocate');
$employ_start_date = $request->get('employ_start_date');
$employ_file = $request->get('employ_file');
$now = new DateTime();
DB::insert('INSERT INTO onlineapplication
(position_name,firstname,middlename,lastname,email,homenumber,phonenumber,employmentstatus,relocate,starting_date,destination,file_img_name,Status)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',[
$firstname,
$lastname,
$middlename,
$email,
$home_number,
$contact_num,
$job,
$employ_status,
$employ_relocate,
$employ_start_date,
$employ_file
]);
return response()->json('Successfully inserted');
}
When form tag is used, the submit will trigger the default behaviour that is based on the method provided and the action url.
as in your example you are handling the data explicitly you should prevent the default behaviour.
add the below code in handle submit
handleSubmit(e) {
e.preventDefault();
...
...
}
this will prevent the default behaviour.
Improvement for state update:
you don't need individual functions to update the input value to state this can be combined in one function.
to combine, provide the input name same as state name.
this.state ={
"f_name": '',
"l_name": '',
...
}
<input name="f_name" ... onChange={this.handleInputChange}/>
<input name="l_name" .. onChange={this.handleInputChange}/>
handleInputChange(e){
let target = e.target;
let name = target.name;
let value = target.value
this.setState({[name]: value})
}
for more info refer this link.
First, I just want to introduce to you to the arrow function in JavaScript (ES6). Declaring private methods like this:
handle_fname = (e) =>
{
this.setState({
f_name:e.target.value,
})
}
will save you time from unnecessary binding in the constructor.
Regarding your question, you missed to show the content of your this.handleSubmit(). Without this, I can assume that the form submit fired a get call since you failed to put method attribute in your <form/> tag, and without indicating your method attribute will result to default get method. Get method when used, data submitted will be visible in the page address field of your browser.
EDIT
You already added your handleSubmit() in your question, and it looks okay. If data is still shown in the address field of your browser, try adding method="post" in your form tag like this:
<form onSubmit={this.handleSubmit} method="post">

Resources