Skip to content

Instantly share code, notes, and snippets.

@eightyfive
Last active February 15, 2017 09:32
Show Gist options
  • Save eightyfive/63121e1ebb683ba5ec5243d818084213 to your computer and use it in GitHub Desktop.
Save eightyfive/63121e1ebb683ba5ec5243d818084213 to your computer and use it in GitHub Desktop.
jQuery [data-ajax] API
$(document).on('click', '[data-ajax]', function (ev) {
var $this = $(this)
var data = $this.data()
var redirect = $this.prop('href') || data.redirect
// `settings` must follows jQuery.ajax API
var settings = data.ajax
ev.preventDefault()
$.ajax(settings).done(function () {
if (redirect && redirect !== '#') {
window.location.href = redirect
}
})
})

We want to do a PUT request marking a booking as cancelled and then redirecting to /my-bookings.

HTML (Twig)

<a href="/my-bookings" data-ajax="{{ {
    url: '/bookings/123/cancel',
    method: 'PUT'
  }|json_encode }}">Cancel booking</a>

CSRF (Laravel)

Don't forget to pass CSRF token in headers.

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': '{{ csrf_token() }}'
    }
})

Alternatively pass _token parameter in settings.data object.

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