Skip to content

Instantly share code, notes, and snippets.

@saiury92
Last active September 16, 2015 04:50
Show Gist options
  • Save saiury92/0cf59ab9ac3addf2b4c3 to your computer and use it in GitHub Desktop.
Save saiury92/0cf59ab9ac3addf2b4c3 to your computer and use it in GitHub Desktop.
Perform cross-origin resource sharing POST request. Hides the use of XDomainRequest for IE from the caller if running in IE. When submitting via IE, the JSON representation of the form data is encoded in Base64 in order to safely send it as a query parameter. The server side needs to implement a Base64 decode strategy in order to get at the form…
/*global webapp, XDomainRequest, Base64*/
webapp.Util = webapp.Util || {};
(function() {
'use strict';
webapp.Util.corsPost = function(url, form, successCallback, errorCallback) {
if (!window.XDomainRequest) {
var deferred = $.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify($(form).getFormData())
});
$.when(deferred).then(
function() {
successCallback();
},
function(error) {
errorCallback(error);
}
);
} else {
var xdr = new XDomainRequest();
xdr.open('POST', url + '?content=' + Base64.encode(JSON.stringify($(form).getFormData())));
xdr.send();
xdr.onerror = function() {
errorCallback();
};
xdr.onload = function() {
successCallback();
};
}
};
/**
* Encodes a form into a JavaScript object with properties/value pairs for each form field. The fields must
* have a "name" attribute.
*
* @return {Object}
*/
$.fn.getFormData = function() {
var unindexedArray = this.serializeArray();
var indexedArray = {};
$.map(unindexedArray, function(n){
indexedArray[n.name] = n.value;
});
return indexedArray;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment