I am making some validations in the Registry of a page that I am doing with MVC
, so I want to validate that the username does not exist in my database, if this name exists, a warning should appear as soon as the person writes the name in the input without the need to send the entire form to give the error, I am using Ajax
and jQuery
to validate this, but it does not work for me.
It gives me the following warning through the browser console:
Warning: count(): Parameter must be an array or an object that implements Countable
Here I leave a screenshot of everything that appears in the console:
The code I'm doing is the following:
$("#usuarioRegistro").change(function(){
var usuario = $("#usuarioRegistro").val();
var datos = new FormData();
datos.append("validarUsuario", usuario);
$.ajax({
url:"views/modules/ajax.php",
method:"POST",
data: datos,
cache: false,
contentType: false,
processData: false,
success:function(respuesta){
console.log("Respuesta de PHP: "+respuesta);
if(respuesta == 0){
$("label[for='usuarioRegistro'] span").html('<p>Este Usuario ya Existe</p>');
}else{
$("label[for='usuarioRegistro'] span").html("");
}
}
});
});
ajax.php module:
<?php
require_once "../../controllers/controller.php";
require_once "../../models/crud.php";
class Ajax{
public $validarUsuario;
public function validarUsuarioAjax(){
$datos = $this->validarUsuario;
$respuesta = MvcController::validarUsuarioController($datos);
echo $respuesta;
}
}
$aux = new Ajax();
$aux->validarUsuario = $_POST["validarUsuario"];
$aux->validarUsuarioAjax();
?>
Controller:
//Validar Usuario Existente
//------------------------------------
public static function validarUsuarioController($validarUsuario){
$datosController = $validarUsuario;
$respuesta = Datos::validarUsuarioModel($datosController, "usuarios");
if(count($respuesta["usuario"]) > 0){
echo 0;
}else{
echo 1;
}
}
Model:
public static function validarUsuarioModel($datosModel, $tabla){
$stmt= Conexion::conectar()->prepare("SELECT usuario FROM $tabla WHERE usuario=:usuario");
$stmt->bindParam(":usuario", $datosModel, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch();
$stmt->close();
}
}
It should be noted that it $respuesta["usuario"]
contains characters that come from fetch()
the model, which returns an array so I don't understand why it gives me a warning with the function count()
, php
if someone knows what I have wrong it would be very helpful! Thanks in advance.
Your problem is that it
Datos::validarUsuarioModel
returns a value that cannot be applied to the count since it is possibly a numeric value, a string or a boolean, try changing yourif
, it may also be that it is returning a valuenull
Example: