Skip to content

Instantly share code, notes, and snippets.

@swuecho
Created April 18, 2014 23:54
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 swuecho/11068937 to your computer and use it in GitHub Desktop.
Save swuecho/11068937 to your computer and use it in GitHub Desktop.
define({
initFullFormAjaxUpload: function() {
// Once the FormData instance is ready and we know
// where to send the data, the code is the same
// for both variants of this technique
function sendXHRequest(formData, uri) {
var xhr = new XMLHttpRequest();
// Set up events
xhr.addEventListener('readystatechange', onreadystatechangeHandler, false);
// Set up request
xhr.open('POST', uri, true);
xhr.send(formData);
}
// Handle the response from the server
function onreadystatechangeHandler(evt) {
var status = null;
try {
status = evt.target.status;
} catch (e) {
return;
}
if (status == '200' && evt.target.responseText) {
var result = document.getElementById('result');
result.innerHTML = '<p>The server saw it as:</p><pre>' + evt.target.responseText + '</pre>';
}
}
var form = document.getElementById('form-id');
form.onsubmit = function() {
// FormData receives the whole form
var formData = new FormData(form);
// We send the data where the form wanted
var action = form.getAttribute('action');
// Code common to both variants
sendXHRequest(formData, action);
// Avoid normal form submission
return false;
}
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment