Abort an Ajax request

Asked

Viewed 338 times

1

In a situation where I use the ASP.NET MVC, can cancel a request AJAX depending on the response of a modal? I am doing something like this:

function atualizaStatus(sel, id) {
    var $status = sel.value;
    var $idAluno = id;

    var ajax = $.ajax({
        type: "POST",
        traditional: true,
        url: '@Url.Action("AtualizaStatus", "Turmas")',
        data: { id: $idAluno, status: $status },
        beforeSend: function () {
            bootbox.confirm({
                title: "Confirma",
                locale: "br",
                message: "Deseja alterar status do aluno?",
                callback: function (result) {
                    if (result == false) {
                        ajax.abort();
                        bootbox.hideAll();
                        return false;
                    }
                }
            })
        },
        error: function () {
            alert("Algo deu errado, tente novamente mais tarde.")
        }
    });
}

That one bootbox is a custom modal of the style of confirm (ok and cancel).

In that logic beforeSend was to execute before sending the request to Controller, but when I do debug when he passes by beforeSend, he sends the request to the Controller and only then it calls the modal, before even waiting for the user’s response.

Why does this occur and how to get around this situation? That is how to make the system wait for the modal response and only then pass on to Controller the request or cancel it?

1 answer

3


Just reverse the order, the way you did, the beforeSend performs previously but it will not wait for the callback modal.

function atualizaStatus(sel, id) {
    var $status = sel.value;
    var $idAluno = id;

    bootbox.confirm({
        title: "Confirma",
        locale: "br",
        message: "Deseja alterar status do aluno?",
        callback: function (result) {
            if (result == false) {
                bootbox.hideAll();
                return false;
            }

            $.ajax({
                type: "POST",
                traditional: true,
                url: '@Url.Action("AtualizaStatus", "Turmas")',
                data: { id: $idAluno, status: $status },
                error: function () {
                    alert("Algo deu errado, tente novamente mais tarde.")
                }
            });
        }
    });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.