I am on admin area, I have a form to create admins, with user (unique id on MySQL), name and password, the form:
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Crear Administrador</h3>
</div>
<div class="box-body">
<form role="form" name="crear-admin" id="crear-admin" method="post" action="insertar-admin.php">
<div class="box-body">
<div class="form-group">
<label for="usuario">Usuario</label>
<input type="text" class="form-control" id="usuario" name="usuario" placeholder="Usuario">
</div>
<div class="form-group">
<label for="nombew">Nombre</label>
<input type="text" class="form-control" id="nombew" name="nombre" placeholder="Tu nombre">
</div>
<div class="form-group">
<label for="contraseña">Contraseña</label>
<input type="password" class="form-control" id="contraseña" name="contraseña" placeholder="Contraseña para iniciar sesión">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<input type="hidden" name="agregar-admin" value="1">
<button type="submit" class="btn btn-primary">Añadir</button>
</div>
</form>
</div>
<!-- /.box-body -->
</div>
I use insertar-admin.php to insert into db and get a JSON, if statement inserted, respuesta = 'exito'
, if not, respuesta = 'error'
, here's the first problem, when insert into db is correct, it works, but when not, I cant get else message, tried with other options, affected_rows
, $result = $stmt->execute();
for true or false bool, but I cant get false, here's the code:
<?php
if (isset($_POST['agregar-admin'])) {
$nombre = $_POST['nombre'];
$usuario = $_POST['usuario'];
$password = $_POST['contraseña'];
$opciones = array(
'cost' => 12
);
$password_hashed = password_hash($password, PASSWORD_BCRYPT, $opciones);
try {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include_once 'funciones/funciones.php';
$stmt = $conn->prepare("INSERT INTO admins (nombre, usuario, password) VALUES (?,?,?)");
$stmt->bind_param("sss", $nombre, $usuario, $password_hashed);
$stmt->execute();
$id_registro = $stmt->insert_id;
if ($id_registro > 0) {
$respuesta = array(
'respuesta' => 'exito',
'id_admin' => $id_registro
);
} else {
$respuesta = array(
'respuesta' => 'error',
);
}
$stmt->close();
$conn->close();
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
}
And this sends to admin-ajax.js to generate a visual response for the user using SweetAlert2, here's the code:
$(document).ready(function() {
$('#crear-admin').on('submit', function(e) {
e.preventDefault();
var datos = $(this).serializeArray();
$.ajax({
type: $(this).attr('method'),
data: datos,
url: $(this).attr('action'),
dataType: 'json',
success: function(data) {
var resultado = data;
if (resultado.respuesta == 'exito') {
swal(
'Correcto!',
'El administrador se creó correctamente!',
'success'
)
} else {
swal(
'Error',
'Hubo un error!',
'error'
)
}
}
})
});
});
With correct insertion it's OK, I get the Correct message and insert, but when error, I don't get nothing, how can I fix?