AJAX with IF ELSE in response

1

Good I am using an AJAX so that the clients register in the web and now I have added a query to him to know if this user already has been registered, step to detail how or I am doing:

AJAX

     <script>
      $(function(){
          $("#formuploadajax1").on("submit", function(e){
              e.preventDefault();
              var f = $(this);
              var formData = new FormData(document.getElementById("formuploadajax1"));
              formData.append("dato", "valor");
              //formData.append(f.attr("name"), $(this)[0].files[0]);
              $.ajax({
                  url: "incluCuenta/insertar-cliente.php",
                  type: "post",
                  dataType: "html",
                  data: formData,
                  cache: false,
                  contentType: false,
                  processData: false
              })
                  .done(function(res){
                    if(res=="1"){
                        toastr["info"]("Registro exitoso!", "Mensaje")
                             setTimeout(function () {
                             window.location.href = "login.php"; //will redirect to your blog page (an ex: blog.html)
                         }, 1500); //will call the function after 2 secs
                    }else{
                        $("#mensaje").html(res);
                        toastr["info"]("Utiliza otro usuario!", "Mensaje")
                    }
                  });
          });
      });
    </script>

Here the insertar-cliente

<?php include "../conexion/conexion.php" ?>
<?php

    mysqli_set_charset("utf8");
    $results = 'SELECT * FROM Usuarios';
    $rec = mysqli_query($mysqli, $results);
    $verificar_usuario = 0;

    while($results = mysqli_fetch_object($rec))
    {
        if($results->Username == $_POST['email'])
        {
            $verificar_usuario = 1;

        }
    }

    if($verificar_usuario == 0)
    {

    $name = $_POST['name'];
    $email = $_POST['email'];
    $telefono = $_POST['telefono'];
    $movil = $_POST['movil'];
    $nif = $_POST['nif'];
    $direccion = $_POST['direccion'];
    $postal = $_POST['postal'];
    $poblacion = $_POST['poblacion'];
    $provincia = $_POST['provincia'];
    $pass = $_POST['pass'];
    $sexo = $_POST['sexo'];
    $fecha=date('y,m,d');



$results = "INSERT INTO Usuarios (Fecha, Sexo, Nombre, Password, Username, Direccion, Postal, Poblacion, Provincia, Telefono, Movil, Dni, intestado) 
VALUES ('$fecha', '$sexo', '$name', '$pass', '$email', '$direccion', '$postal', '$poblacion', '$provincia', '$telefono', '$movil', '$nif', '1')";

if ( !mysqli_query($mysqli, $results)) {
  die( 'Error: ' . mysqli_error() );
   }


   }

    else
    {
        echo '<span class="error">Este usuario ya ha sido registrado anteriormente.</span>';
    }

?>

What fails me is that the ajax notifies me, but I need you to notify me if this is repeated the User makes a response and if it is correct is the other answer, something I have done but it does not work well. If it is busy the user leaves the poster of this user and it is already inserted in the bd, but if everything is correct, it shows only the opposite toast and if it is inserted in the bd.

    
asked by Miguel 07.09.2018 в 10:12
source

1 answer

0

Apart from the syntactic and programming errors that I have detected, I noticed that at no time did you return the number "1" waiting to receive the XHR request launched from javascript. This prevents your code from working correctly if the user registers in the database.

On the other hand, the second most serious error I have encountered has been the concatenation of strings without escaping an SQL query. This causes your query to fail if a field has a quote inside it or, worse, may suffer the serious security problems associated with the SQL injection .

To solve this we can use prepared queries or use mysqli::real_escape_string() (as I have done, so no I have to make many changes to the code) to previously escape the content of the variable.

I have left comments for the code to explain the modifications I have made and the errors I have detected:

<?php
/* Aquí olvidaste el ; del final */
include "../conexion/conexion.php";

/* Aquí olvidaste poner como primer parámetro la conexión mysqli */
mysqli_set_charset($mysqli, "utf8");
$results = 'SELECT * FROM Usuarios';
$rec = mysqli_query($mysqli, $results);
/* Si falló la consulta informamos de ello */
if ($rec === false) {
    die('ERROR SQL: ' . htmlspecialchars(mysqli_error($mysqli)));
}
while ($results = mysqli_fetch_object($rec)) {
    /* Hacemos una comparación en minúsculas (si quieres) */
    if(mb_strtolower($results->Username) == mb_strtolower($_POST['email'])) {
        /* No es necesario marcar y luego comprobar, podemos finalizar aquí mismo */
        die('<span class="error">Este usuario ya ha sido registrado anteriormente.</span>');
    }
}

/* Escapamos las cadenas correctamente para evitar tanto inyección SQL
    como cadenas mal formadas */
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
$telefono = mysqli_real_escape_string($mysqli, $_POST['telefono']);
$movil = mysqli_real_escape_string($mysqli, $_POST['movil']);
$nif = mysqli_real_escape_string($mysqli, $_POST['nif']);
$direccion = mysqli_real_escape_string($mysqli, $_POST['direccion']);
$postal = mysqli_real_escape_string($mysqli, $_POST['postal']);
$poblacion = mysqli_real_escape_string($mysqli, $_POST['poblacion']);
$provincia = mysqli_real_escape_string($mysqli, $_POST['provincia']);
$pass = mysqli_real_escape_string($mysqli, $_POST['pass']);
$sexo = mysqli_real_escape_string($mysqli, $_POST['sexo']);
/* Te aconsejo fechas en formato YYYY-MM-DD, localiza sólo al mostrar */
$fecha = date('y,m,d');

$results = "
    INSERT INTO Usuarios (
        Fecha,
        Sexo,
        Nombre,
        Password,
        Username,
        Direccion,
        Postal,
        Poblacion,
        Provincia,
        Telefono,
        Movil,
        Dni,
        intestado
    ) VALUES (
        '$fecha',
        '$sexo',
        '$name',
        '$pass',
        '$email',
        '$direccion',
        '$postal',
        '$poblacion',
        '$provincia',
        '$telefono',
        '$movil',
        '$nif',
        '1'
    )
";
if (mysqli_query($mysqli, $results) === false) {
    /* Aquí olvidaste poner como primer parámetro la conexión mysqli */
    die('Error SQL: ' . htmlspecialchars(mysqli_error($mysqli)));
}
/* Si todo ha ido bien tu aplicación espera encontrar el texto "1" */
echo "1";
    
answered by 07.09.2018 / 11:20
source