Skip to content

Instantly share code, notes, and snippets.

@DanWebb
Last active July 1, 2016 03:24
Show Gist options
  • Save DanWebb/ab38e993b54d12a76053 to your computer and use it in GitHub Desktop.
Save DanWebb/ab38e993b54d12a76053 to your computer and use it in GitHub Desktop.
API AJAX methods: HTML5 IE10+ form+Image upload ajax, Generic AJAX calls, AJAX from forms.
// ajax call from a form
api.formAjax = function($form, type, callback) {
var data = {};
$form
.find('input:not([type="submit"], [type="file"]), textarea, select')
.each(function() {
data[$(this).attr('name')] = $(this).val();
})
.promise()
.done(function() {
api.ajax($form.attr('action'), data, type, callback);
})
;
};
// HTML5 IE10+ form+Image upload ajax
api.formImageAjax = function(form, callback) {
var formData = new FormData(form);
$.ajax({
type:'POST',
url: $(form).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
if(data.error) {
api.notification.show('alert-danger', data.message);
} else {
if(data.warning) {
api.notification.show('alert-warning', data.message);
}
callback(data);
}
},
error: function(data){
console.log("error");
console.log(data);
}
});
};
// generic AJAX calls
api.ajax = function(url, params, type, callback) {
$.ajax(url, {
dataType: type,
data: params
})
.done(function(data) {
if(data.error) {
api.notification.show('alert-danger', data.message);
} else {
if(data.warning) {
api.notification.show('alert-warning', data.message);
}
callback(data);
}
})
.fail(function(a,b,c){
console.log(a);
console.log(b);
console.log(c);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment