Why does my ajax only work when I want?

-4

I have a page that is a mixture of HTML and php that when I click the submit button, JavaScript fires, takes all information and calls a function that activates an ajax to call a php file.

It seems very simple though, it just works only when you want! I no longer know what to think or do, it simply has times that ajax calls the class, it executes everything correctly and returns to request.done to execute another function, and another time it simply returns request.fail to none apparent reason.

I do not know if it is relevant, but some information I pass by session of the HTML page to the php file. And I've noticed that at times it works, sessions can not reach the last page. This last page is called when ajax can execute and it enters 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" ?> );

    }

});

the function that contains 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 "it works when you want", after all I'm a programmer myself. What I meant is that one hour works and another does not. I thought it was easy to understand.

    
asked by anonymous 16.12.2016 / 14:43

2 answers

2

This is good works whenever you want, if it goes wrong how it will work. This happens for three reasons.

  • First do not know the concept of ajax right. (Concept: Ajax is an asynchronous call that updates part of the DOM)
  • Second reason, a call can work, time yes, time not, when! The DOM tree is outdated, so it (function) tries to update a certain part and the instruction that updates, does not know that that part does not even exist, to avoid this use container tags, where it will always be present .
  • Third reason, the function tag itself does not exist, ie the image, button form, has not even created the event as it can.

Following this line, this is no longer the case

  

"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.
    
16.12.2016 / 20:40
1

Try to place the success or error check inside the ajax itself in this way;

$.ajax({

    //códigos do ajax atual

    success : function(result){

        mudaPagina(result);   

    }
});

It is interesting to do the tests with the Inspect Open Element, in the "Network" or "Network" tab, in order to see the requests that the browser is making live, as well as the answers to those requests.

    
16.12.2016 / 20:26