Why does my ajax only work when you want?

Asked

Viewed 205 times

-4

I have a page that is mixing HTML with php that when I click the button submit, Javascript is triggered, takes all the information and calls a function that activates an ajax to call a php file.

It seems very simple, however, it simply works only when it wants! I no longer know what to think or do, simply have sometimes ajax calls the class, it performs everything right and returns to the request.done to perform another function, and again it simply returns to the request.fail for no apparent reason.

I don’t know if it’s relevant, but some information I pass through Sesssion from the HTML page to the php file. And I’ve noticed that sometimes it works, the Sesssions can’t get to the last page. This last page is called when ajax can run and enters the request.done.

Javascript code to get information:

window.cartao = 0;
data= new Date();
ano = data.getFullYear();
mes = data.getMonth() + 1;
var form = document.getElementById('caixa');
var cardNum = document.getElementById('cardNumber');
var expMes = document.getElementById('selectExpData');
var expAno = document.getElementById('InputAno');

var verifCod = document.getElementById('verifCode');
var nameCard = document.getElementById('nomeBox');

form.addEventListener('submit', function(e) {
    var resultado = verificaCampos(ano, mes, cardNum, expMes, expAno, verifCod, nameCard);
    if(resultado == false) {
        e.preventDefault();
    } else {

        transacaoCredito(cardNum.value, expAno.value, expMes.value, verifCod.value, nameCard.value, window.cartao, <?php echo "$totalReal";?>, <?php echo "$Amount" ?> );

    }

});

function containing the ajax

function transacaoCredito(cardNum, expAno, expMes, verifCod, nameCard, cartao, valorReal, amount) {
var request = $.ajax({
 type: "post",
 url: "_classes/creditoTransacao.php",
 data:
 {
 "cardNum":cardNum,
 "expAno":expAno,
 "expMes":expMes,
 "verifCod":verifCod,
 "nameCard":nameCard,
 "cartao":cartao,
 "valorReal":valorReal,
 "amount":amount
 }
 });

 request.done(function (result) {
     mudaPagina(result);
 });

 request.fail(function () {
    alert('Ocorreu um erro, por favor tente novamente mais tarde');
 });
}

And the php file:

<?php
session_start();
$cardNum = $_POST['cardNum'];
$expAno = $_POST['expAno'];
$expMes = $_POST['expMes'];
$verifCod = $_POST['verifCod'];
$nameCard = $_POST['nameCard'];
$cartao = $_POST['cartao'];
$valorReal = $_POST['valorReal'];
$valorReal = number_format($valorReal, 2, "", "");
$valorReal = (integer) $valorReal;
$Amount = $_POST['amount'];
/*teste
$Amount = number_format($Amount, 2, "", "");
$Amount = (integer) $Amount;
//teste*/

$ourOrderId = $_SESSION['ourOrderId'];
$ourReturnUrl = $_SESSION['ourReturnUrl'];
$ourNotifyUrl = $_SESSION['ourNotifyUrl'];
$CurrencyCode = $_SESSION['CurrencyCode'];

/*$ourOrderId = $_POST['ourOrderId'];
$ourReturnUrl = $_POST['ourReturnUrl'];
$ourNotifyUrl = $_POST['ourNotifyUrl'];
$CurrencyCode = $_POST['CurrencyCode'];*/


require_once ('../vendor/autoload.php');
require_once ('../_classes/conexaoBanco.php');
use Cielo\Cielo;
use Cielo\CieloException;
use Cielo\Transaction;
use Cielo\Holder;
use Cielo\PaymentMethod;
use Cielo\Consultation;
$merchantId = '1111111111';
$merchantKey = '11111111111111111111111111111111111111111111111111111';
$cielo = new Cielo($merchantId, $merchantKey, Cielo::TEST);
$holder = $cielo->holder($cardNum, $expAno, $expMes, Holder::CVV_INFORMED, $verifCod);
$order = $cielo->order($ourOrderId, $valorReal);//$valorReal
switch ($cartao) {
    case 'visa':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::VISA, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'master':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::MASTERCARD, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'discover':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::DISCOVER, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'amex':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::AMEX, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'diners':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::DINERS, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'jcb':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::JCB, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'elo':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::ELO, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'aura':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::AURA, PaymentMethod::CREDITO_A_VISTA);
        break;
}

$transaction = $cielo->transaction($holder, $order, $paymentMethod, $ourReturnUrl, Transaction::AUTHORIZE_WITHOUT_AUTHENTICATION, true);

try {
    $transaction = $cielo->transactionRequest($transaction);
    if ($transaction->getAuthorization()->getLr()==0){
        $tid = $transaction->getTid();
        $consultation = $cielo->consultation($tid);
        try {
            $consultationResponse = $cielo->consultationRequest($consultation);
            if (is_object($consultationResponse)) {
                $status = $consultationResponse->getStatus();

                switch ($status) {
                    case 0:
                        $statusBanco = "Transação criada com sucesso";
                        break;
                    case 1:
                        $statusBanco = "Transação em Andamento";
                        break;
                    case 2:
                        $statusBanco = "Transação Autenticada";
                        break;
                    case 3:
                        $statusBanco = "Transação não Autenticada";
                        break;
                    case 4:
                        $statusBanco = "Transação Autorizada";
                        break;
                    case 5:
                        $statusBanco = "Transação não Autorizada";
                        break;
                    case 6:
                        $statusBanco = "Transação Capturada";
                        break;
                    case 9:
                        $statusBanco = "Transação Cancelada";
                        break;
                    case 10:
                        $statusBanco = "Transação em Autenticação";
                        break;
                    case 12:
                        $statusBanco = "Transação em Cancelamento";
                        break;
                    default:
                        $statusBanco = "Não há status da transação";
                }
                $mensagem = $consultationResponse->getAuthorization()->getMessage();
                $data = $consultationResponse->getAuthorization()->getDateTime();
                $data = new DateTime($data);
                $valorTotal = $consultationResponse->getAuthorization()->getTotal();
                $array = str_split($valorTotal);
                $antes = substr($valorTotal, 0
                    , count($array) - 2);
                $depois = substr($valorTotal, (count($array) - 2));
                $valorTotal = $antes . "." . $depois;

                $banco = new conexaoBanco();
                $banco->salvaBanco($tid,$cardNum,$nameCard,$valorTotal,$Amount,$statusBanco,$mensagem,$data->format('Y-m-d H:i:s'), $ourOrderId);

            }
        } catch (CieloException $ex) {
            echo "Erro[" . $ex->getCode() . "]: " . $ex->getMessage();
        }

        echo $status;

    } else {
        throw new CieloException($transaction->getAuthorization()->getLr());
    }
} catch(CieloException $ex) {
    echo "Erro[".$ex->getCode()."]: ".$ex->getMessage();
}
?>

Edit: Guys, I know there’s no such thing as "works when you want," after all, I’m also a programmer. What I meant was that one time it works and another time it doesn’t. I thought it was easy to understand.

  • Welcome to Sopt, have you tried using the Firebug to see what’s going on?

  • I’ll test to find out, thanks for the contribution!

  • Man, there’s no such thing as working when you want.

  • When it fails, in the first argument of request.fail has a property responseText what is there? , there is the return of the error that happened in PHP.

  • I tried to give an Alert no request.fail to display this.responseText and it returned Undefined. Help me if you have done wrong, please.

2 answers

2


This one works when it wants to, if it does wrong how it will work. This happens for three reasons.

  • First of all, they don’t really know the concept of ajax. (Concept: Ajax is an asynchronous call that updates part of the DOM)
  • Second reason, a call can work, time in, time out, when! The DOM tree is outdated, so it(function) tries to update a certain part and the instruction that updates, doesn’t know that part doesn’t even exist, to avoid this use container tags, where she will always be present.
  • Third reason, the function tag itself does not exist, ie the image, formulary button, not even created the event as you can use.

Following that line, it doesn’t happen anymore

"works when you want"

I set an example, just to try to illustrate the scenario

<div id="tag1">

</div>
<javascript>
    atualize(tag2); 
</javascript>
atualize tag no html acima, então chama ajax, quando ajax retorna não acha e não atualiza pois ela não existe 

<div id="tag1">
   <p id="tag2">
   </p>
</div>
Caso 3.
<javascript>
   atualize(tag2); 
</javascript>
script que arma o evento para chamar a função, não esta escutando, mesmo que a tag chamada tag2 exista.
  • Can you be clearer on the second reason, please? And how come the function tag doesn’t exist? PS: I’m sorry if I don’t have the same understanding as you.

  • I put example, see if it helps

1

Try to put the success or error check inside the ajax itself, this way;

$.ajax({

    //códigos do ajax atual

    success : function(result){

        mudaPagina(result);   

    }
});

It is interesting to do the tests with the Inspect Element open, in the tab "Network" or "Network", to be able to see the requests that the browser is doing live, as well as the responses of these requests.

Browser other questions tagged

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