Skip to content

Instantly share code, notes, and snippets.

@laracasts
Last active March 2, 2019 09:42
Show Gist options
  • Save laracasts/7dbebcfc4c6e0b5d5513 to your computer and use it in GitHub Desktop.
Save laracasts/7dbebcfc4c6e0b5d5513 to your computer and use it in GitHub Desktop.
Little JavaScript helpers for a Laravel app.
{{ Form::open(['data-remote', 'data-remote-success-message' => 'I have now done the thing.']) }}
{{ Form::text('name') }}
{{ Form::submit('Submit', ['data-confirm' => 'Are you sure?']) }}
{{ Form::close() }}
(function() {
var submitLaravelRequest = function(e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
var url = form.prop('action');
$.ajax({
type: method,
url: url,
data: form.serialize(),
success: function() {
var message = form.data('remote-success-message');
if (message) {
$('.flash').html(message).fadeIn(300).delay(2500).fadeOut(300);
}
}
});
e.preventDefault();
};
var confirmAction = function(e) {
var input = $(this);
input.prop('disabled', 'disabled');
// Or, much better, use a dedicated modal.
if ( ! confirm(input.data('confirm'))) {
e.preventDefault();
}
input.removeAttr('disabled');
};
// And bind functions to user events.
$('form[data-remote]').on('submit', submitLaravelRequest);
$('input[data-confirm], button[data-confirm]').on('click', confirmAction);
})();
@laracasts
Copy link
Author

Or, if you want to take this a step further... https://gist.github.com/laracasts/ecfe6c102e1aead0ee44

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment