KAZI OMAR FARUK
KAZI OMAR FARUK

Reputation: 1

Debounce function means e.preventDefault on click and submit event no longer working

Debounce function e.preventDefault not working. When I click submit button it's refreshing the whole page. Actually, I want when I will click submit button one or more times it sends only one ajax request to the server for 1000ms, so for that, I am using a debounce function.

Please see the code below.


    const debounce = (fn, delay) => {
        let timeoutID;
        return function(...args){
            if(timeoutID){
                clearTimeout(timeoutID);
            }
            timeoutID = setTimeout(() => {
                fn(...args);
            }, delay);
        };
    };


    
    $(document).ready(function () {

        $('#myID').on('click', debounce(e => {
            e.preventDefault();
            console.log('clicked');
        }, 2000))

    
        $(document).on('submit','.likeID',debounce(e => { 
            e.preventDefault();
            let _this = $(this);
            let _likeCount = _this.find('#likeCount').val();
            let uid = $(this).data('uid');
            let _token = $("input[name='_token']").val();
            // console.log(uid);
            $.ajax({
                type: "PUT",
                url: "{{route('like.user')}}",
                data: {
                    id:uid,
                    _token:_token
                },
                success: function (response) {
                    if(response == true){
                        _likeCount++
                    _this.addClass('unlikeID');
                    _this.removeClass('likeID');
                    _this.find('.heart').addClass("is-active");
                    _this.find('#likeCount').val(_likeCount);
                    _this.find('span').text(_likeCount);
                    }
                }
            });
        },1000));

Please anyone help...

Upvotes: 0

Views: 382

Answers (1)

nullptr
nullptr

Reputation: 4474

I can't check this right now, but it should be solved if you move the preventDefault call outside debounce:

 $(document).on('submit','.likeID',() => {
         e.preventDefault();
         debounce(e => { 
            let _this = $(this);
            ...
         })() // You have to call the function here.

Note that I'm calling the function using () in the last like.

Upvotes: 0

Related Questions