Created
July 20, 2013 15:52
-
-
Save mateuszkocz/6045518 to your computer and use it in GitHub Desktop.
Sending form with AJAX. Source: http://blog.ponyfoo.com/2013/07/09/getting-over-jquery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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