javascript - How do i check for duplicate entries in a database using pdo, php and ajax?
one text
i made this form in datatables with php and ajax in which i need to warn the user for trying to insert a duplicated entry, but for some reason when i have the check code datatables throws me the error "DataTables warning: table id=tablaProveedor - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1", but only when the if check exists, when i comment it the code works well, i don't know if is because i'm using a switch to make the crud work
The code i used for that case is
case 8: //cliente
$repe = $conexion->prepare("SELECT cedula FROM cliente WHERE cedula= '$cedula'");
$repe->execute();
if($repe->rowCount()>0){
echo '<script>alert("La cedula ya existe")</script>';
break;
}else{
$consulta = "INSERT INTO cliente (nombrec, tipo, cedula, telefono, direccion, ciudad) VALUES('$nombrec', '$tipo', '$cedula', '$telefono', '$direccion', '$ciudad') ";
$resultado = $conexion->prepare($consulta);
$resultado->execute();
$consulta = "SELECT * FROM cliente ORDER BY id DESC LIMIT 1";
$resultado = $conexion->prepare($consulta);
$resultado->execute();
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
break;
and the insert in ajax looks like
$(document).ready(function() {
$('select').select2({
dropdownParent: $('#formProveedor')
});
var id_pro, opcion;
opcion = 10;
tablaProveedor = $('#tablaProveedor').DataTable({
"ajax":{
"url": "bd/crud.php",
"method": 'POST',
"data":{opcion:opcion},
"dataSrc":""
},
"columns":[
{"data": "id"},
{"data": "nombrec"},
{"data": "tipo"},
{"data": "cedula"},
{"data": "telefono"},
{"data": "direccion"},
{"data": "ciudad"},
{"defaultContent": "<div class='text-center'><div class='btn-group'><button class='btn btn-primary btn-sm btnEditar'><i class='material-icons'>edit</i></button></div></div>"}
]
});
var fila;
$('#formProveedor').submit(function(e){
e.preventDefault();
nombrec = $.trim($('#nombrec').val());
tipo = $.trim($('#tipo').val());
cedula = $.trim($('#cedula').val());
telefono = $.trim($('#telefono').val());
direccion = $.trim($('#direccion').val());
ciudad = $.trim($('#ciudad').val());
$.ajax({
url: "bd/crud.php",
type: "POST",
datatype:"json",
data: {id_pro:id_pro, nombrec:nombrec, tipo:tipo, cedula:cedula, telefono:telefono, direccion:direccion, ciudad:ciudad ,opcion:opcion},
success: function(data) {
tablaProveedor.ajax.reload(null, false);
}
});
$('#modalCRUD').modal('hide');
});
$("#btnNuevo").click(function(){
opcion = 8;
id_pro=null;
$("#formProveedor").trigger("reset");
$(".modal-header").css( "background-color", "#17a2b8");
$(".modal-header").css( "color", "white" );
$(".modal-title").text("A?�adir proveedor");
$('#modalCRUD').modal('show');
});
the case 10 is just a select * from clientes.
everything works when i don't have that if doing something, i've been googling for days what to do but now i feel like my head is going to explode, please help
Source