I'm trying to create a log in system with php, jquery, ajax, json, it validates if there are empty fields, but as soon as I complete and submit the form the ajax call fails, the console shows the json array in the response text, so the problem is not the php part, but it says parsererror, I don't know how to resolve this, I'm still a rookie. Here's my code:
index.php
<html>
<head>
<title></title>
<link rel="stylesheet" href="/ajax/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/ajax/css/style.css"/>
<meta charset="UTF-8">
</head>
<body>
<section>
<div class="container">
<div class="row">
<div class="col-xs-12" id="titulo">
<h3>Ajax Login</h3>
</div>
<div class="col-xs-10 col-xs-offset-1">
<form id="formulario" action="php/validator.php" method="post">
<div class="col-xs-4 col-xs-offset-4" id="formPart">
<label for="user">Nombre de Usuario</label>
<input type="text" id="user" name="user" class="form-control">
<div class="user"></div>
</div>
<div class="col-xs-4 col-xs-offset-4" id="formPart">
<label for="pass">Nombre de Usuario</label>
<input type="password" id="pass" name="pass" class="form-control">
<div class="pass"></div>
</div>
<div class="col-xs-4 col-xs-offset-4" id="formPart">
<input type="submit" value="Iniciar Sesión" class="btn btn-success">
</div>
</form>
<div class="col-xs-4 col-xs-offset-4" id="response"></div>
</div>
</div>
</div>
</section>
<script src="/ajax/js/jquery2.js"></script>
<script src="/ajax/js/bootstrap.min.js"></script>
<script src="/ajax/js/ajax.js"></script>
<script>
$(document).ready(function(){
setTimeout(function(){
$('#user').focus();
}, 700);
});
</script>
</body>
</html>
validator.php
<?php
if($_POST){
$required = array('user', 'pass');
$validation = array('user' => 'Debes Ingresar tu Nombre de Usuario', 'pass' => 'Debes Ingresar tu Contraseña');
$error = array();
$inputs = array();
foreach($required as $key){
if(array_key_exists($key, $_POST)){
if(empty($_POST[$key])){
$error[$key] = $validation[$key];
}
else{
$inputs[$key] = $_POST[$key];
}
}
else{
$error[$key] = $validation[$key];
}
}
if(!empty($error)){
$array = array('error' => true, 'fields' => $error);
}
else{
$user = $inputs['user'];
include 'log.php';
if(user($user)){
$message = '<div class="alert alert-success">Bienvenido '.$inputs['user'].'</div>';
$array = array('success' => true, 'message' => $message);
}
else{
$messages = '<div class="alert alert-success">El usuario '.$inputs['user'].' no existe</div>';
$array = array('fail' => true, 'messages' => $messages);
}
}
header('Content-Type: application/json');
echo json_encode($array);
}
else{
header("Location: ../index.php");
}
log.php
<?php
function user($user){
include 'conexion.php';
$conexion = conectar();
mysqli_set_charset($conexion, "utf8");
$query = "Select * from user where username = '{$user}'";
$result = mysqli_query($conexion, $query);
$total = mysqli_num_rows($result);
if($total > 0){
return true;
}
else{
return false;
}
}
conexion.php
<?php
function conectar(){
error_reporting(0);
$server = 'localhost';
$user_db = 'root';
$pass_db = '';
$db = 'user';
$conexion = new mysqli($server, $user_db, $pass_db, $db);
if($conexion->connect_errno){
echo 'Error de Conexion. Código de Error: '.$conexion->connect_errno;
}
else{
return $conexion;
}
}
ajax.js
$('#formulario').on('submit', function(){
$('#formulario .warn').remove();
$('form input').removeClass('warning');
var thisForm = $(this),
url = thisForm.attr('action'),
type = thisForm.attr('method'),
data = thisForm.serializeArray();
$.ajax({
url: url,
type: type,
data: data,
dataType:"json",
crossDomain: true,
success: function(response){
if(response.error){
$.each(response.fields, function(index, value){
$('.' + index).hide().html('<span class="warn">' + value + '</span>').fadeIn(700);
$('#' + index).addClass('warning');
});
}
else if(response.success){
$('#formulario').fadeOut(700, function(){
$('#response').hide().html(response.message).fadeIn(700);
});
}
else{
$('#response').hide().html(response.messages).fadeIn(700);
}
},
error: function(xhr, textStatus){
console.log(xhr);
console.log(textStatus);
}
});
return false;
});
I'm getting the following error in console:
ajax.js:53: Object {readyState: 4, responseText: "{"fail":true,"messages":"El usuario aa no existe(the user aa doesn´t exist)</div>"}", status: 200, statusText: "OK"} ajax.js:54: parsererror
i got this from the console:
SyntaxError: Unexpected token at Object.parse (native) at n.parseJSON (http://localhost/ajax/js/jquery2.js:4:6225) at zb (http://localhost/ajax/js/jquery2.js:4:8172) at z (http://localhost/ajax/js/jquery2.js:4:11629) at XMLHttpRequest. (http://localhost/ajax/js/jquery2.js:4:15507)
it seems i'm getting a malformed request, that's what i read in another question
