Ajax does not run correctly

1

The structure of my project is as follows:

and I have the following code:

Login_inicio.html

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/bootstrap-grid.css">
    <link rel="stylesheet" href="css/bootstrap-reboot.css">
    <link rel="stylesheet" href="css/fa-brands.css">
    <link rel="stylesheet" href="css/fa-regular.css">
    <link rel="stylesheet" href="css/fa-solid.css">
    <link rel="stylesheet" href="css/fontawesome.css">
    <link rel="stylesheet" href="css/style.css">
    <title>Iniciar Sesión</title>
</head>
<body>
    <header id="header-login" class="card-header justify-content-center">
        <h1 class="text-center">Login Form</h1>
        <h3 class="text-center"><small>Bootstrap e ImageICon</small></h3>
    </header>
    <section id="login-inicio" class=" container text-center">
        <div class="row-form-inicio row justify-content-center">
            <div class="form-login-inicio col-6">   
                <div class="row bg-white titulo-login justify-content-center">
                    <h2 id="Titulo-login">Iniciar Sesión</h2>
                </div>
                <form>
                    <div class="input-group input-div-login-user">
                        <span class="input-group-addon">
                            <i class="fas fa-user"></i>
                        </span>
                        <input type="text" class="form-control" name="correo-usuario" id="correo-usuario" placeholder="Correo">
                    </div>
                    <div class="input-group input-div-login-password">
                        <span class="input-group-addon">
                            <i class="fas fa-lock"></i>
                        </span>
                        <input type="text" class="form-control" name="password-login" id="password-login" placeholder="Contraseña">
                    </div>
                    <div class="row justify-content-center btn-div-login">
                        <button class="btn btn-outline-primary" name="btn-login" id="btn-login" onclick="login()">Iniciar Sesión</button>
                    </div>
                </form>
            </div>
        </div>              
        </div>          
    </section>  
    <footer id="footer-login">
        <div class="row row-footer justify-content-center align-items-center">
            <h3>Administración <small>2016-2018</small></h3>
        </div>
    </footer>
    <script type="text/javascript" src="js/jquery-3.2.1.js"></script>
    <script type="text/javascript" src="js/ajax/ajaxlogin.js"></script>
</body>
</html>

ajaxlogin.js

function login(){
if ($('#correo-usuario').val()===""|| $('#password-login').val()==="") {
    alert("Hay campos vacios");

}else{

    var correo= $('#correo-usuario').val();
    var password =$('#password-login').val();
    alert(correo+" "+password)  

        ajaxLogin(correo,password)  ;
    }
}

function ajaxLogin(correo,password){
$.ajax({
url: 'php/consultas.php',
type: 'POST',
/*En el data se define los datos que se mandaran y como, en este ejemplo se envian los datos como tipo JSON*/
data: {Correo: correo, Password: password},
/*El beforSend se ejecuta hasta que se reciba una respuesta del servidor, mientras tanto mostrara el mensaje "Cargando..."*/
beforeSend: function(){
    //Hay que modificar esto
    document.getElementById('Titulo-login').innerHTML='Cargando...';    
}
})
/*Si la consulta se realizo con exito*/
.done(function(data) {
console.log("success");



})
/*Si la consulta Fallo*/
.fail(function() {
alert("Fallo");
})
}

consultas.php

<?php
sleep(3);
session_start();
include("bd/conexionbd.php");
$correo=$_POST['Correo'];
$contrasena=$_POST['Password'];

$cmd= $conn->prepare('SELECT CONCAT(empleados.nombre_empleado," ",empleados.apellido_paterno," ", empleados.apellido_materno) as NombreEmpleado, tipo_usuario.rol FROM tipo_usuario inner join usuarios on tipo_usuario.id_tipousuario=usuarios.id_tipo_usuario inner join empleados on usuarios.id_empleado=empleados.id_empleado inner join estado on empleados.id_estado=estado.id_estado where estado.estado=1 and correo=? and contraseña=?');
$cmd->bind_param('ss',$correo_usuario, $usuario_cont);
$correo_usuario=$correo;
$usuario_cont=$contrasena;
$cmd->execute();

/*Vinculamos las variables al resultado*/
$cmd->bind_result($user,$rol);
/*Almacenar el resultado*/
$cmd->store_result();
/*Se comprueba si hay resultados*/
if ($cmd->num_rows>0) {
/*Se obtienen los resultados guardados*/
$cmd->fetch();
//Seteamos el header de "content-type" como "JSON" para que jQuery lo reconozca como tal
  header('Content-Type: application/json');
  /*Se llena el aray con los resultados*/
  $datos = array('Usuario' => $user, 'Rol' => $rol);
  /*Se crea el objeto JSON y se agregan los datos del Array*/
  echo json_encode($datos,JSON_FORCE_OBJECT);
  /*Se crea la session*/
  $_SESSION['usuario']=$user;
}else{
echo 'no hay resultados';
}

?>

The problem is that the ajax does not execute the php code and always shows me the fault and after reviewing it several times I can not find the error.

Debugging shows me the following message:

This same structure had been used in other projects and had not had problems.

Inside the ajax function I put an alert to serve as a flag and it shows me that the mail and password of the function ajaxLogin if assigned, the problem is between the ajax data and the php queries

    
asked by Ferny Cortez 21.12.2017 в 05:13
source

2 answers

4

What is happening behind the scenes and may be your error is that the attribute type by default of the button is submit and that event is not being controlled so the form is sent % with the values of the text boxes but with the names of the form ie (user-mail, password-login) and not with Correo and Password .

To solve can setear the type a button on the button

<button class="btn btn-outline-primary" name="btn-login" id="btn-login" 
        onclick="login()"  type="button" >Iniciar Sesión</button>
    
answered by 21.12.2017 / 06:32
source
0

When you send the data with the request AJAX

  

alert (mail + "" + password)

Does that alert correctly show you the data taken from your inputs ?

If you show the data correctly that alert , I think the error may be that you need to specify the datatype in your method AJAX staying as follows:

function ajaxLogin(correo,password){
$.ajax({
url: 'php/consultas.php',
type: 'POST',
dataType: 'JSON',
/*En el data se define los datos que se mandaran y como, en este ejemplo se envian los datos como tipo JSON*/
data: {Correo: correo, Password: password},
/*El beforSend se ejecuta hasta que se reciba una respuesta del servidor, mientras tanto mostrara el mensaje "Cargando..."*/
beforeSend: function(){
    //Hay que modificar esto
    document.getElementById('Titulo-login').innerHTML='Cargando...';    
}
})
/*Si la consulta se realizo con exito*/
.done(function(data) {
console.log("success");



})
/*Si la consulta Fallo*/
.fail(function() {
alert("Fallo");
},'json');

In case the error persists, try in your PHP to establish the 2 variables of mail and password with data from your BD, and you enter from your browser making reference to that PHP to see that the error is not this there.

    
answered by 21.12.2017 в 06:23