-1

I'm trying to stop an active ajax request when I click on checkbox. i active an ajax which calls every second to a url, but when i uncheck the checkbox, I was trying to close the ajax request. I tried with listener.abort(); and it doesnt work and also i added xhr.abort() and nothing happend. Any suggestion?

    function listener() {
    $.get('http://localhost:3000/get-value', function (dataf) {
        if (dataf.result != "") {
            $.ajax({
                url: "http://localhost:8000/login",
                data: { pId: dataf.result },
                type: "POST",
                success: function (result) {
                    if (result.name != "") {
                        $.get('http://localhost:3000/close-conn');
                        window.location.href = result.url;
                    }
                }
            });
        }
        setTimeout(listener, 1000);
    });
}

function GetCheckStatus() {
    var flag = chkAuto.GetValue();

    if (flag) {
        $.ajax({
            url: "http://localhost:3000/open-conn",
            type: "GET",
        });
        listener();
    } else {
        $.ajax({
            url: "http://localhost:3000/close-conn",
            type: "GET",

        });
        // Doesnt work
        listener.abort();
    }
}
pmaddi
  • 449
  • 5
  • 18
Johan Sánchez
  • 165
  • 3
  • 17

1 Answers1

1

You're calling the .abort() method on the function, not the actual request object. Try something like this instead.

Define variables for the $.get request and the setTimeout, then abort/clear them as needed.

var xhr, timeout;

function listener() {
    xhr = $.get('http://localhost:3000/get-value', function (dataf) {
        if (dataf.result != "") {
            $.ajax({
                url: "http://localhost:8000/login",
                data: { pId: dataf.result },
                type: "POST",
                success: function (result) {
                    if (result.name != "") {
                        $.get('http://localhost:3000/close-conn');
                        window.location.href = result.url;
                    }
                }
            });
        }
        timeout = setTimeout(listener, 1000);
    });
}

function GetCheckStatus() {
    var flag = chkAuto.GetValue();

    if (flag) {
        $.ajax({
            url: "http://localhost:3000/open-conn",
            type: "GET",
        });
        listener();
    } else {
        $.ajax({
            url: "http://localhost:3000/close-conn",
            type: "GET",

        });

        //Cancel the current request and prevent the next one from being triggered
        xhr.abort();
        clearTimeout(timeout);
    }
}
Reza Karami
  • 505
  • 1
  • 5
  • 15