Created
April 18, 2014 23:54
-
-
Save swuecho/11068937 to your computer and use it in GitHub Desktop.
This file contains 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
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