I will allow myself to point out some things in your code. I'll read it line by line and I'll give you some recommendations:
die
a horror .
Particularly die
I do not like. Much less if the Ajax request is waiting for a JSON object.
To avoid the horror of die
in case of error, we will save the message in an array that will be our response to the server.
You are not verifying the variables of $_POST
One is sometimes naive when he schedules and believes that everything will turn out as one thinks, but it turns out that it is not always like that. Then, evaluate your variables $_POST
The eternal problem of the SQL injection . Your code is one of those that hackers love to inject malicious code into your database. It applies prepared queries, which is why the MySQLi extension exists.
When answering JSON from the server, indicate it in the header.
jQuery recommends using done
, fail
and other relatives to handle Ajax requests. The well-paid success
even if you do not believe it, is obsolete since jQuery 3.
Now let's apply those five patches to your code:
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "data_estudiantes";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_errno) {
/*Parche 1*/
$arrRespuesta=array("error"=>"Error de conexión: ".mysqli_connect_error());
}else{
$nombre = $_POST['nombre'];
$apellidos = $_POST['apellidos'];
$cedula = $_POST['cedula'];
/*Parche 2*/
if ($nombre !== '' && $apellidos !== '' && $cedula !== '')
{
/*Parche 3*/
$sql = "insert into estudiantes (nombre, apellidos, cedula) VALUES (?,?,?)";
$stmt=$conn->prepare($sql);
/*Evaluar si la preparación tuvo éxito*/
if ($stmt)
{
/*
* Pasar parámetros separados de la instrucción SQL
* la letras "sss" indican el tipo de cada dato que se va a insertar
* s: String, si es una cadena , i: Integer, si fuera un entero, etc
* Ejecutar
*/
$stmt->bind_param("sss", $nombre,$apellidos,$cedula);
$stmt->execute();
$id = $conn->insert_id;
$arrResultado=array('id'=>$id, 'nombre' => $nombre, 'apellidos' => $apellidos, 'cedula' => $cedula);
}else{
$arrResultado=array("error"=>"Hubo un error con la consulta");
}
}else{
$arrResultado=array("error"=>"Hay variables vacías en el POST");
}
}
/*
*Parche 4:
*Si observas, hasta ahora no hemos impreso nada
*hemos ido guardando todo en un arreglo
*y ahora lo imprimimos, así aseguramos que siempre el servidor
*responderá con un JSON que podremos evaluar del lado del cliente
*/
header('Content-Type: application/json');
echo json_encode($arrResultado);
?>
jQuery / JS
We will use done
, fail
to update the code. That will be Patch 5:
var request = $.ajax
({
url: "addEstudent.php",
method: "POST",
data: {nombre: nombre, apellidos:apellido, cedula:cedula},
dataType: "json"
});
request.done(function( data )
{
console.log(data);
/*
*Verificamos que no hay error en la respuesta
*para eso en PHP fuimos controlando el código
*y creando un array con los datos o con mensajes de error
*/
if (!data.error)
{
var fila =
'<tr id="'+data.id+'">
<td>'+ data.nombre +'</td>
<td>'+ data.apellidos+'</td>
<td>'+data.cedula+'</td>
<td><button class="btn btn-danger eliminarBtn" data-idest = "'+data.id+'">
<i class="glyphicon glyphicon-remove"></i></button></td>
</tr>';
$('tbody').append(fila);
$('#contador').html($('tbody tr').length);
}else{
/*
*Aquí podremos acceder al mensaje de error
*que viene en el JSON mediante data.error
*si quieres, puedes imprimirlo en alguna parte del DOM
*/
console.log(data.error);
}
});
request.fail(function( jqXHR, textStatus )
{
alert( "La petición Ajax falló: " + textStatus );
});