I'm trying change the HTTP Status Code in PHP if something goes wrong on a SQL Query and receive this HTTP Status Code on AJAX call via jQuery.
Why is not working? This is the registro.php file content:
<?php
require_once('conexao.php'); // the connection to db
$telefone = $_POST['telefone']; // get the tel number
$celular = $_POST['celular']; // get the cel number
$celular = str_replace(array("(",")","-"," "), "", $celular);
$dddCelular = substr($celular, 0, 2);
$celular = substr($celular, 2, 9);
$telefone = str_replace(array("(",")","-"," "), "", $telefone);
$dddTelefone = substr($telefone, 0, 2);
$telefone = substr($telefone, 2, 8);
// after split the region code I check if is equal to a specify region, in case 11
if($dddCelular == "11" || $dddTelefone == "11") {
$sql = "INSERT INTO `bigdata` (`id`, `origem`, `nome`, `dddtelefone`, `telefone`, `dddcelular`, `celular`, `email`, `obsadm`, `observacoes`, `timestampcadastro`) 
VALUES (NULL, 'renovacnh', '".utf8_decode($nome)."', '".$dddTelefone."', '".$telefone."', '".$dddCelular."', '".$celular."', '".$email."', '".$horario."', '".$observacoes."', CURRENT_TIMESTAMP);";
if(mysqli_query($conn, $sql)) { mysqli_close($conn); 
echo "OK";
http_response_code(200); // the query is ok! so, change to 200
};
} else {
// var_dump(http_response_code()); // int(200) - default
http_response_code(503); // set a new code
// var_dump(http_response_code()); // int(503) - new code
echo "ERROR";
}
And here is my AJAX script:
<script>
function pixel(data) {
  console.log(data);
  if(data == "OK") {
    alert("It works!");
  } else {
    alert("Fail");
  }
}
function envia() {
$.ajax({
    method: "POST",
    url : "php/registro.php",
    data: {
      "celular": "(21) 95494-3943", // the phone is wrong region code, not 11
      "telefone": "(21) 4494-3943", // the cel is wrong region code, not 11
    },
    success: function (data,xhr) {
       pixel(data);
       console.log(xhr); // trow success
    },
    error: function (error,xhr) {
       console.log(error);
       console.log(xhr);
    }
});
}
envia();
</script>
So in the end, I'm trying to check via AJAX if response is equal to "OK" and for somehow the if() it's failing. And not validate as OK response at all. So I'm trying to use HTTP Status Code to check that on AJAX response somehow.
Any ideas? Thanks!
