Return Javascript before finalizing processing

1

I have this method:

var getCardToken = function () {
    var passa = true;
    var code = false;
    var acardNumber= $("#ContentPlaceHolder1_txtNmCartao").val();
    var acvv=  $("#ContentPlaceHolder1_txtCodigoDeSeguranca").val();
    var aexpirationMonth= $("#ContentPlaceHolder1_cmbMesCartao").val();
    var expirationYear = $("#ContentPlaceHolder1_cmbAnoCartao").val();
    var naoTitular = $("#ContentPlaceHolder1_chkNaoTitular")[0].checked;
    var cpfTitular = $("#ContentPlaceHolder1_txtCpfTitular").val();
    var foneTitular = $("#ContentPlaceHolder1_txtFoneTitular").val();
    var dataNascimento = $("#ContentPlaceHolder1_txtDataNascimento").val();

    if (!naoTitular) { // se for o titular do cartao quem esta efetuando a compra

        if (acardNumber == "" && acardNumber != null) {
            passa = false;

        };

        if (acvv == "" && acvv != null) {
            passa = false;

        };

        if (aexpirationMonth == "Mês" && aexpirationMonth != null) {
            passa = false;
        };


        if (expirationYear == "Ano" && expirationYear != null) {
            passa = false;
        };


    } else { // se nao for o titular do cartao devemos olhar outros campos.


        if (cpfTitular == "" && cpfTitular != null) {
            passa = false;

        };

        if (foneTitular == "Mês" && foneTitular != null) {
            passa = false;
        };


        if (dataNascimento == "Ano" && dataNascimento != null) {
            passa = false;
        };

    }

    if (passa) {

        //se os dados estao preenchidos corretamente

        PagSeguroDirectPayment.createCardToken({

            cardNumber: $("#ContentPlaceHolder1_txtNmCartao").val(),
            cvv: $("#ContentPlaceHolder1_txtCodigoDeSeguranca").val(),
            expirationMonth: $("#ContentPlaceHolder1_cmbMesCartao").val(),
            expirationYear: $("#ContentPlaceHolder1_cmbAnoCartao").val(),
            success: function (response) {
                //token gerado, esse deve ser usado na chamada da API do Checkout Transparente
                $("#ContentPlaceHolder1_hideTcc").val(response.card.token);
               console.log($("#ContentPlaceHolder1_hideTcc").val());
                code = true;

            },
            error: function (response) {
                console.error(response);
                alert("Ocorreu um erro ao verificar os dados do cartão, por favor atualize a pagina e tente novamente!");
                code = false;

            },
            complete: function (response) {

            }

        });


    };
    return code;
};

The call to it occurs like this:

<asp:button ID="cmdAvancarEndereco" runat="server" cssclass="btn btn-success btn-lg" OnClientClick="return getCardToken();"  text="Avançar >"></asp:button>

I got the hint that if I put it like this: OnClientClick="return getCardToken();" Code-Behind is only executed if the return of function JS is true

But what is happening and that the function executes to the end, returns false, and then returns to this point (as if executed twice):

PagSeguroDirectPayment.createCardToken({

            cardNumber: $("#ContentPlaceHolder1_txtNmCartao").val(),
            cvv: $("#ContentPlaceHolder1_txtCodigoDeSeguranca").val(),
            expirationMonth: $("#ContentPlaceHolder1_cmbMesCartao").val(),
            expirationYear: $("#ContentPlaceHolder1_cmbAnoCartao").val(),
            success: function (response) {
                //token gerado, esse deve ser usado na chamada da API do Checkout Transparente
                $("#ContentPlaceHolder1_hideTcc").val(response.card.token);
               console.log($("#ContentPlaceHolder1_hideTcc").val());
                code = true;

            },
            error: function (response) {
                console.error(response);
                alert("Ocorreu um erro ao verificar os dados do cartão, por favor atualize a pagina e tente novamente!");
                code = false;

            },
            complete: function (response) {

            }

        });

These methods are callback functions, the problem is that I could only return some value (true / false) after executing the callback functions which is the one that is defined whether or not it goes to codebehind.

Is this normal behavior? Is there a way to execute this callback before returning the function?

    
asked by anonymous 14.02.2017 / 14:35

2 answers

1

In fact what happens is: What the pagseguro is doing "under the cloth" is an ajax request, ajax is asynchronous, that is, it takes a while to complete, and if the javascript is to wait until the request to be completed your browser would become "frozen" while processing the request.

So we use callbacks, which is basically a function that is executed when the request ends, this involves success, error, or two.

When it arrives at the point where it has return code; the request has not yet finished, you still have no response from the server, so the code / function of success or error is executed, so you have this impression of "getting back to that point".

Roughly speaking it's like you've scheduled the function to run later.

    
14.02.2017 / 15:42
1

They are the schizitices of JS ... this java script code exacts everything "at the same time" then it executes the error code: and complete:

You have to pass the error as a function parameter

createCardToken({jsonstuf}, function(err, result){.....

if (err) {console.error(<erros, mensagens..>)....

What you're looking for is something like this:

document.querySelector('form').onsubmit = formSubmit

function formSubmit (submitEvent) {
  var name = document.querySelector('input').value
  request({
    uri: "http://example.com/upload",
    body: name,
    method: "POST"
  }, postResponse)
}

function postResponse (err, response, body) {
  var statusMessage = document.querySelector('.status')
  if (err) return statusMessage.value = err
  statusMessage.value = body
}

This is a site reference link If I can write something better that makes more sense I'll post again.

    
14.02.2017 / 15:24