Skip to content

Instantly share code, notes, and snippets.

@Sparksss
Created March 11, 2019 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sparksss/ed7feb74339de8f1be32f7196909face to your computer and use it in GitHub Desktop.
Save Sparksss/ed7feb74339de8f1be32f7196909face to your computer and use it in GitHub Desktop.
this is simple sending form data.
// This is function which send data
// In this variant, we need invoke preventDefault() function
// in first line code our function.
const sendData = (event) => {
event.preventDefault(); // this line need for cancel default behavior and send via ajax
// take our form
const form = event.target;
// create object for parsing to json
const data = {};
// add data, from form
// use names out form fields for access inputs
data.name = form.name.value;
data.phone = form.phone.value;
data.email = form.email.value;
// and send data
fetch(form.action, {
method: “POST”,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
// check result
.then(response => response.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error))
};
<form onsubmit="return sendData(event);" action="https://my.example.com/save" method="post">
<input type="text" name="name" >
<input type="number" name="phone">
<input type="email" name="email">
<! — For supports all browsers we should use input element →
<input type="submit" value="Send">
</form>
<form onsubmit=”return sendData(this);” action=”https://my.example.com/save” method=”post”>
<input type=”text” name=”name” >
<input type=”number” name=”phone”>
<input type=”email” name=”email”>
<! — For supports all browsers we should use input element →
<input type=”submit” value=”Send”>
</form>
// in first line code our function.
const sendData = (this) => {
// take our form
// create object for parsing to json
const data = {};
// add data, from form
// use names fields for access inputs
data.name = this.name.value;
data.phone = this.phone.value;
data.email = this.email.value;
//and send data
fetch(form.action, {
method: “POST”,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
// check result
.then(response => response.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error))
return false; // it's line required for send data.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment