Jquery function executes when I click on a button with back() function?

Asked

Viewed 33 times

2

I have a form that I send to a function with $.ajax That shipping by Ubmit, this works well. The problem is that I have a button that I do a back() to return the page and when I click on that button this function $.ajax is executed as if I click on submit. How to solve this problem ?

Ajax function for sending the form

$('#formEditCatProduto').submit(function (e) {
    e.preventDefault();
    var dados = $(this).serialize();
    //var dados = new FormData($('#formAddEmpresa').get(0));

    $('#btnEditarCatProd').prop('disabled', true);
    $('#btnCancelar').prop('disabled', true);
    $("#errorMessage").hide();

    var loading = $(".imageLoading");
    $(document).ajaxStart(function () {
        loading.show();
    });
    $(document).ajaxStop(function () {
        loading.hide();
    });

    $.ajax({
        accepts: { json: 'application/json' },
        dataType: 'json',
        type: "POST",
        url: "/CategoriaProduto/editAjax",
        data: dados,       
        success: function (data) {
            var status = data["status"];
            var msg = data["msg"];
            if (status === "1") {               
                $("#errorMessage").html(msg);
                $("#errorMessage").prop("class", "alert-success");                
                window.location.replace("/CategoriaProduto/view");
            } else {
                $('#btnEditarCatProd').prop('disabled', false);
                $("#errorMessage").html(msg);
                $("#errorMessage").prop("class", "alert-danger");
            }
            $("#errorMessage").show()            
        },
        error: function (xhr, status) {
            $("#btnEditarCatProd").prop("disabled", false);
            $("#btnCancelar").prop("disabled", false);
            $("#errorMessage").html("Erro tentando editar categoria de produto :(");
            $("#errorMessage").prop("class", "alert-danger");
            $("#errorMessage").show()
        }
    });

});

Buttons

<div class="pull-right">                        
                        <input type="submit" class="btn btn-warning" id="btnEditarCatProd" value="Gravar" />                        
                        <button id="btnCancelar" class="btn btn-danger" onclick="window.history.back()">Cancelar</button>                         
                    </div>

1 answer

5


Knuckle type="button" on that button. If you don’t do this the browser thinks the type is type="submit" which is the default behavior defined in the browser if the attribute type is not defined.

<button id="btnCancelar" type="button" class="btn btn-danger" onclick="window.history.back()">Cancelar</button>                         

Browser other questions tagged

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