Last active
March 2, 2019 09:42
-
-
Save laracasts/7dbebcfc4c6e0b5d5513 to your computer and use it in GitHub Desktop.
Little JavaScript helpers for a Laravel app.
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
{{ 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() }} |
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
(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); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or, if you want to take this a step further... https://gist.github.com/laracasts/ecfe6c102e1aead0ee44