Skip to content

Instantly share code, notes, and snippets.

@eob
Created September 1, 2016 18:14
Show Gist options
  • Save eob/867f410476b290596370cd2b07c56ec6 to your computer and use it in GitHub Desktop.
Save eob/867f410476b290596370cd2b07c56ec6 to your computer and use it in GitHub Desktop.
function ajax(method, url, body, params, cb) {
var ia = document.createElement('iron-ajax');
ia.url = url;
ia.method = method;
var self = this;
if (body) {
var formData = new FormData();
if (body) {
for (var param in body) {
if (typeof body[param] == 'object') {
formData.append(param, JSON.stringify(body[param]));
}
else {
formData.append(param, body[param]);
}
}
}
ia.body = formData;
}
ia.addEventListener('response', function (resp) {
if (resp && resp.detail && resp.detail.response) {
var theResponse;
if (typeof resp.detail.response == 'string') {
try {
var r = JSON.parse(resp.detail.response);
theResponse = r;
}
catch (e) {
theResponse = resp.detail.response;
}
}
else {
theResponse = resp.detail.response;
}
if (theResponse.error) {
cb(resp.detail.response);
}
else {
cb(null, resp.detail.response);
}
}
else {
var res = { error: true, msg: "Could not post data" };
cb(res);
}
});
ia.addEventListener('error', function (resp) {
var res = { error: true, msg: "Could not post data -- got error response." };
cb(res);
});
ia.generateRequest();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment