Abort an Ajax request

1

In a situation where I use ASP.NET MVC , can you cancel a AJAX request depending on the response of a modal? I'm 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.")
        }
    });
}

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

In logic this beforeSend was to execute before sending the request to Controller , but when I debug when it goes through beforeSend , it sends request to Controller and only then it calls the modal, before even waiting for the user's response.

Why does this happen and how do you get around this situation? In other words, how do you expect the system to wait for the modal response and only then pass the request to Controller or cancel it?

    
asked by anonymous 20.01.2016 / 14:02

1 answer

3

Just reverse the order, the way you did it, beforeSend executes previously but it will not wait for callback of 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.")
                }
            });
        }
    });
}
    
20.01.2016 / 14:19