Skip to content

Instantly share code, notes, and snippets.

@shellus
Created June 22, 2017 09:52
Show Gist options
  • Save shellus/42f45ed27e66c98e4d657f736c79889b to your computer and use it in GitHub Desktop.
Save shellus/42f45ed27e66c98e4d657f736c79889b to your computer and use it in GitHub Desktop.
$('form[target=ajax]').live('submit', function(){
var data = [],
$this = $(this),
self = this,
onajax = window[$this.attr('onajax')],
call = window[$this.attr('call')];
if(typeof call!='function'){
call=function(){}
}
if('function'==typeof onajax){
try{
if(onajax.call(this)===false) return false;
}catch(err){
call.call(self, err);
return false;
}
}
$(':input[name]', this).each(function(){
var $this=$(this),
value=$this.data('value'),
name=$this.attr('name');
if($this.is(':radio, :checkbox') && this.checked==false) return true;
if(value===undefined) value=this.value;
data.push({name:name, value:value});
});
$.ajax({
url:$this.attr('action'),
async:true,
data:data,
type:$this.attr('method')||'get',
dataType:$this.attr('dataType')||'json',
headers:{"x-form-call":1},
error:function(xhr, textStatus, errThrow){
call.call(self, errThrow||textStatus);
},
success:function(data, textStatus, xhr, headers){
var errorMessage=xhr.getResponseHeader('X-Error-Message');
if(errorMessage){
call.call(self, decodeURIComponent(errorMessage), data);
}else{
call.call(self, null, data);
}
}
});
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment