简体   繁体   中英

Why is my ajax request executed twice if have only on call?

I have an ajax request for a script in php, in this script I do several checks of the past values and right after I call a DAO method to save the information in the db, so far everything normal, the problem has been that when a of the validations fail I return an error with the echo json_enconde ($error) and use the exit(). What can go wrong? Well, even with the exit some strange behaviors happen, yes the $error is returned, but even with this return, the success function is triggered twice, one returns it to me and the other the script continues to be called and saves the infos in the db.

AJAX

$.ajax({
    method: "POST",
    url: "ajax/compra-acao.php",
    data: {usuario_id: usuario, cod: c, qtd: quantidade, acao: acao1},
    dataType: 'JSON',
    success: function(response){
            console.log(response)
            document.getElementById('btnComprar').disabled = false
            return 0;
        }
    },
    error: function(response, status, error){
        alert(response.responseText);
    }
})

SCRIPT PHP

    <?php

if(!isset($_POST['usuario_id']) || !isset($_POST['cod']) || !isset($_POST['qtd']) || !isset($_POST['acao'])){
    echo json_encode($retorno['erro'] = 'Houve um erro ao processar sua solicitação. POST');
    exit();
}

include_once('../PDO/acaoDAO.php');
include_once('../PDO/usuarioDAO.php');

$usuario = new UserBD();
$acao = new Acao();

$retorno = [];

$usuario = $usuario->getUserById($_POST['usuario_id']);

if(!$usuario){
    $retorno['erro'] = 'Houve um erro ao processar sua solicitação';
    echo json_encode($retorno);
    exit();
}

if(!password_verify($usuario[0]['cpf'], $_POST['cod'])){
    $retorno['erro'] = 'Hoje não, espertinho';
    echo json_encode($retorno);
    exit();
}

if($_POST['qtd'] < 1){
    $retorno['erro'] = 'Quantidade inválida';
    echo json_encode($retorno);
    exit();
}

$precoAcao = $acao->getPrecoAcaoById($_POST['acao']);

if(!$precoAcao){
    $retorno['erro'] = 'Ação inválida';
    echo json_encode($retorno);
    exit();
}

$saldo = $acao->getSaldoDinheiroById($_POST['usuario_id']);

if($saldo < (double) $precoAcao * (int) $_POST['qtd']){
    $retorno['erro'] = 'Saldo insuficiente';
    echo json_encode($retorno);
    exit();
}

$result = $acao->compraAcao($_POST['qtd'], $_POST['acao'], $_POST['usuario_id'], $saldo[0]['quantidade'], $precoAcao[0]['preco']);

if(isset($result['erro'])){
    echo json_encode($result);
    exit();
}else{
    echo json_encode([true]);
    exit();
}

?>

When I use console.log(response) I get two exits, the first with the array with the error and right after a return [true] , which is when everything went right with the inserts in the db.

CONSOLE.LOG

{erro: "Hoje não, espertinho"} erro: "Hoje não, espertinho" __proto__: Object
preco.js:65 

[true] 0: true length: 1 __proto__: Array(0)

EDIT:

With the help of friends in the comments I could see that I was targeting efforts in the wrong place, when evaluating the tab network in the browser I could see that the request was being sent more than 1 time, with the wrong value and with the right value too, that's why the double execution.

After debugging better I could find the cause of the problem, it was really happening because of Google Chrome. The code is ok.

I wanted to force the sending of wrong data to the server and I was doing it using the function of inspecting chrome element and placing any value manually, it happens that when changing the value in this way Chrome ends up "stacks" or "adds" one more call the function of AJAX, if I change this way several times it will stack more and more calls, I don't know if it should be the correct behavior

The HTML with the call:

<button id="btnVender" onclick="venderAcao(210,'5mbZz5LpULCs9oKT3BHbzUiW',3)" class="btn btn-vender mt-xl-0 mt-lg-3 mt-0">Vender</button>

if I change any of these values of the onclick function it is as if I have two functions being called in the onclick, the original and the modified one

Thank you all for your help

You can try to use exit; with out '()' or return false; or return; and put to befor your exit the

http_response_code(500);
echo json_encode('ERROR');
exit;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM