Return Javascript before finishing processing

Asked

Viewed 300 times

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 him occurs like this:

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

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

However what is happening and that Function runs until the end, returns false, and then returns to this point (as if it ran 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 callback functions that is there that is defined whether or not goes to codebehind.

Is that normal behavior? There is a way to execute this callback before returning to Function?

2 answers

1

It’s the J’s little tricks... this java script code exacutes 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 seek I believe to be something more or less in this format:

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 reference from the website http://callbackhell.com/ In case I can write something better that makes more sense.

  • The problem, is not that it is giving error, but rather that type, it passes the callback function without executing it kind seems that it reads but does not execute there after it arrives at the end of the function where it has the code return code; then he goes back to pag callback

  • As I was saying... javascript is a strange language.... to do this you have to go nesting callbacks.

  • well I’ll edit the answer a little to see if it helps... from what I understand you want a function to create values from a card token.. right?

  • Try putting 'async: false, ' in your AJAX function, will happen what @Neuber Oliveira said, but you will be able to better analyze the return of the call before callback!

  • So the problem is that I’m not the one running ajax, I don’t even have access to the function it comes from a JS lib that Pagseguro itself offers.. the only thing I can do and pass the parameters he asks me (card number, expiration date, cvv), and callback methods..

1


In fact what happens is the following: What Pagseguro is doing "under the table" is an ajax request, ajax is Ncrono, IE, it takes a while to complete, and if javascript were to wait until the request is completed your browser would be "frozen" while processing the request.

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

When you get to where you are return code; o the request has not yet finished, Voce still had no response from the server, so ends the code/function of success or error is executed, so you have this impression of "go back to that point".

Grossly speaking it is as if you have scheduled the function to be executed later.

  • I got it, man... I figured it was because of the callback, and there’s no way to lock the processing to get the callback feedback ?

  • not that I know of

Browser other questions tagged

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