Last active
September 16, 2015 04:50
-
-
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…
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
/*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