Skip to content

Instantly share code, notes, and snippets.

@mateuszkocz
Created July 20, 2013 15:52
Show Gist options
  • Save mateuszkocz/6045518 to your computer and use it in GitHub Desktop.
Save mateuszkocz/6045518 to your computer and use it in GitHub Desktop.
<form id='registration' name='registration' action='/register'>
<input type='text' name='username' value='carlos'>
<input type='email' name='email' value='[email protected]'>
<input type='number' name='dob' value='1940'>
<input type='submit' onclick='return sendForm(this.form);'>
</form>
// Create form data and send it with only JS.
var formData = new FormData();
formData.append('username', 'carlos');
formData.append('email', '[email protected]');
formData.append('dob', 1940);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/register', true);
xhr.onload = function(e){
if(this.status === 200){
console.log(this.response);
}
};
xhr.send(formData);
// Take data from the HTML form.
function sendForm(form) {
var formData = new FormData(form);
formData.append('csrf', 'e69a18d7db1286040586e6da1950128c');
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function(e) {
// ...
};
xhr.send(formData);
return false; // we're already submitting the form through AJAX.
}
var form = document.querySelector('#registration');
sendForm(form);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment