Callback is executed in the parameter

Asked

Viewed 39 times

0

function requestAjax(url, metodo, data, successCallback) {
    $.ajax({
        url: url,
        type: metodo,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        statusCode: {
            200: () => {
                successCallback();
            }
        }
    });
}

function adicionarNovaCategoria() {
    if ($("#nova-categoria-input").val() !== '') {
        var categoria = {
            nomeCategoria: $("#nova-categoria-input").val()
        };

        requestAjax("/api/categorias-componente", "POST", categoria, function () {
            showAlertaVerde("Item adicionado!");
            getTodasCategorias();
            $("#nova-categoria-input").val('');
        });

    } else {
        showNomeInvalido();
    }
}

The function I pass as callback in the second function add is executed before entering the function requestAjax.

  • 1

    You don’t understand showAlertaVerde("Item adicionado!");
 getTodasCategorias();
 $("#nova-categoria-input").val(''); is executed before ajax

  • Got it now. But testing here these functions were called after Ajax(?).

1 answer

2


You need to set ajax to asynchronous false.

async: "false"

Browser other questions tagged

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