I have a problem, what happens is that with Ajax I am inserting records in a database asynchronously (without reloading the page) through the $_POST method. Everything is fine when I insert the first record, but when I want to insert another record it is sent 2 times, and every time I enter a new record it is duplicated and so on.
I have tried with a 'return false' when I close 'ajax({});', emptying the variables in the beforeSend, in the success, inside the if and else, and it still doesn't work for me
Form code which is a modal:
<!-- Modal -->
<div class="modal fade" id="formAddVehiculo" tabindex="-1" aria-labelledby="modalTittle" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id="formCrearVehiculo" method="post">
<div class="modal-header">
<h5 class="modal-tittle" id="modalTittle">Agregar nuevo vehículo</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-1">
<input required type="text" class="form-control" name="txtpatente" id="txtpatente" placeholder="Patente del vehículo">
</div>
<div class="mb-1">
<input required type="text" class="form-control" name="txtmarca" id="txtmarca" placeholder="Marca del vehículo">
</div>
<div class="mb-1">
<input required type="text" class="form-control" name="txtmodelo" id="txtmodelo" placeholder="Modelo del vehículo">
</div>
<div class="mb-1">
<input required type="number" min="1886" max="2022" minlength="4" maxlength="4" class="form-control" name="intanio" id="intanio" placeholder="Año del vehículo">
</div>
<div class="mb-1">
<input required type="datetime-local" class="form-control" name="datefecha" id="datefecha" placeholder="">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-success" type="button" id="btnCrearVehiculo">Agregar</button>
<button class="btn btn-danger" type="reset">Borrar</button>
</div>
</form>
</div>
</div>
</div>
<!-- Fin del modal -->
Function code:
$('#btnCrearVehiculo').click(function(e) {
e.preventDefault();
var dataVehiculo = '';
txtpatente = $('#txtpatente').val();
txtmarca = $('#txtmarca').val();
txtmodelo = $('#txtmodelo').val();
intanio = $('#intanio').val();
datefecha = $('#datefecha').val();
const action = 'crearVehiculo';
$.ajax({
url: './app/ajaxVehiculo.php',
type: 'POST',
async: true,
data: {
action:action,
txtpatente:txtpatente,
txtmarca:txtmarca,
txtmodelo:txtmodelo,
intanio:intanio,
datefecha:datefecha
},
beforeSend: function() {
// Deshabilitamos el botón mientras se ejecuta
$("#btnCrearVehiculo").html('Espere...').attr('disabled', 'disabled');
const action = '';
},
success: function(response){
// Volvemos a habilitar el botón
$("#btnCrearVehiculo").html('Agregar').removeAttr('disabled');
// Vaciamos las variables
txtpatente = $('#txtpatente').val("");
txtmarca = $('#txtmarca').val("");
txtmodelo = $('#txtmodelo').val("");
intanio = $('#intanio').val("");
datefecha = $('#datefecha').val("");
if (response == 'notData') {
Swal.fire({
title: "El vehículo que quiere registrar ya existe",
icon: "error"
});
}
else if(response == 'camposVacios')
{
console.log(response);
}
else {
$("#rowsVehiculos").load("#rowsVehiculos");
Swal.fire({
title: "Registro exitoso",
icon: "success"
});
}
},
error: function(response){
console.log('En error: function()');
}
});
return false;
});
I edit the question adding the PHP code, and above in the function adding the validation else if(response == 'emptyfields')
//Arriba de este else if hay otras validaciones
else if( $_POST['action'] == 'crearVehiculo' )
{
$patente=strtoupper($_POST['txtpatente']);
$marca=trim($_POST['txtmarca']);
$modelo=trim($_POST['txtmodelo']);
$anio=trim($_POST['intanio']);
$fecharegistro=$_POST['datefecha'];
if(empty($patente) || empty($marca) || empty($modelo) || empty($anio) || empty($fecharegistro))
{
echo 'camposVacios';
}
else
{
$query = "SELECT * FROM vehiculos WHERE patente = '$patente'";
$query_select = mysqli_query($conexion,$query);
if( !empty($query_select) AND mysqli_num_rows($query_select) > 0 )
{
echo 'notData';
}
else
{
$queryinsert = "INSERT INTO vehiculos (patente,marca,modelo,anio_vehiculo,fecha_registro)
VALUES ('$patente','$marca','$modelo','$anio','$fecharegistro')";
try
{
mysqli_query($conexion,$queryinsert);
echo 'created';
} catch (Exception $e){
echo $e->getMessage();
}
}
}
}
You could check by inspecting the browser element that the click event is not being executed twice. In the network tab it shows you if the call to ajaxVehiculo.php was repeated. You can add after e.preventDefault(), e.stopImmediatePropagation();