Laravel – Ajax “without” jQuery.ajax for each one

Project XGallery có rất nhiều thứ cần ajax. Tất nhiên chuyển sang Vue thì sẽ ngon hơn nhiều. Nhưng còn hạn chế kiến thức, thôi thì xài Ajax tạm.

Vốn dĩ lười, nên mình rất oải khi phải code jQuer.ajax cho từng cái. Mất thời gian vl. Nên thôi tìm cách khác.

                    <span class="float-right">
                         <button type="button" class="btn btn-primary btn-sm ajax-pool"
                                 data-ajax-url="{{route('truyenchon.download.request', $item->id)}}"
                                 data-ajax-command="download"
                         >
                        <i class="fas fa-download mr-1"></i>Download
                        </button>
                    </span>
  • ajax-pool . Class này dùng để chỉ định hook ajax cho element này
  • Quan trọng là mớ data-*
    • data-ajax-url . Attribute này sẽ dùng chỉ định ajax request tới URL nào
    • còn thì thêm các data-* thế nào tuỳ nhu cầu sử dụng

Phần js base

    xgallery.ajax = {
        request: function (data) {
            ajaxUrl = data.ajaxUrl;
            delete data.ajaxUrl;

            jQuery.ajax({
                headers: {
                    'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')
                },
                url: ajaxUrl,
                data: data,
                method: "POST",
                beforeSend: function()
                {
                    jQuery('#overlay').show();
                }
            })
                .done(function (data) {
                    jQuery(this).attr('disabled', true);
                    jQuery('#overlay').hide();
                })
                .fail(function () {
                    jQuery('#overlay').hide();
                })
        },
        init: function () {
            jQuery('body').on('click', '.ajax-pool', function () {
                xgallery.ajax.request(jQuery(this).data());
            })
        }
    }

Simple . Right ?

Phần còn lại thì chỉ việc làm backend ở Controller để xử lý ajax request.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up ↑

%d bloggers like this: