Created
June 17, 2015 17:03
-
-
Save haroldcris/1ea3cb6f9baa1a580bdb to your computer and use it in GitHub Desktop.
A simple Laravel Blade Post wrapper
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
<script src='/packages/promise/promise.js'></script> | |
<script> | |
function postMyData(formName,dialogRef){ | |
return new RSVP.Promise (function(resolve, reject){ | |
var form = $('#' + formName); | |
//add token | |
if($(form).find('input[name="_token"]').length == 0) $(form).append('{{Form::token()}}'); | |
var action = $(form).attr('action'); | |
if (action == undefined ) { return reject(Error('No URL Target'));} | |
if(dialogRef != undefined && typeof dialogRef != 'object' ){ | |
return reject(Error('DialogRef must be an object!')); | |
} | |
if (dialogRef != undefined && dialogRef != ''){ | |
dialogRef.getButton('dialogOkBtn').spin().disable(); | |
} | |
$('.errorHeaderStatus').hide(); | |
$.post(action, form.serialize()) | |
.fail(function(data){ | |
var _err; | |
switch(data.status){ | |
case 400: | |
case 406: | |
_err = JSON.parse(data.responseText).error; | |
break; | |
default: | |
_err = "Error: " + data.status + "<br>" + data.statusText; | |
break; | |
} | |
showPostError(dialogRef,_err); | |
return reject(Error(data['error'])); | |
}) | |
.done(function(data){ | |
var _eventName = $(form).attr('id') + '.submitted'; | |
fireEvent(_eventName); | |
if(typeof data != 'object'){ | |
//return reject(Error('Post request invalid reply')); | |
fireEvent(_eventName + 'WithError'); | |
return reject(Error(data)); | |
} | |
if(data['success'] == "true" || data.success == true){ | |
//console.log('success posting to ' + action); | |
fireEvent(_eventName + 'WithSuccess'); | |
return resolve(data); | |
} else{ | |
// console.log('success posting to ' + action + ' but with error'); | |
showPostError(dialogRef, data['error']); | |
//return reject(Error(data)); | |
return reject(data); | |
} | |
}) | |
.always(function(){ | |
if (dialogRef != undefined && dialogRef != ''){ | |
dialogRef.getButton('dialogOkBtn').stopSpin().enable(); | |
} | |
}); | |
}); | |
} | |
function showPostError(dialogRef, _error){ | |
if (dialogRef != undefined && dialogRef != ''){ | |
var _errStatus = dialogRef.getModalBody().find('.errorHeaderStatus'); | |
if(_errStatus.length == 0){ | |
dialogRef.getModalBody().append('<br><div class="errorHeaderStatus alert alert-danger" style="margin-bottom:0px !important">' + _error + '</div>'); | |
}else{ | |
return $(_errStatus).html(_error).show(); | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment