Ajax does not work

1
  • Container folder:
    • Folder js
      • Sub-Folder ajax
        • JS File ajaxlogin.js
    • Folder php
      • PHP file consultas.PHP
    • HTML file index.html

My code is as follows:

index.html

<!DOCTYPE html>
<html lang="ES-MX">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, Initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/estilo.css">

<title>Login HTML,JS,PHP y MySQL </title>
</head>
<body>

<header class="card-header text-center">
    <h1><strong>Ejemplo Login</strong></h1>
    <h5>HTML, JS, PHP y MySQL</h5>      
</header>
<section class="container">
        <div class="row justify-content-center row-login">
            <div class="col-5 form_login bg-light">
                <div class="row bg-primary text-white justify-content-center"><h3 class="text-center">Iniciar Sesión</h3></div>
                <div id="warning-div" class="row bg-warning justify-content-center display-none">
                    <small id="warning-text" class="text-center">           
                    </small>
                </div>  
                <div class="">
                    <form action="">
                        <div class="form-group">
                            <label for="login">Usuario:</label>
                            <input type="text" name="txtUsuario" class="form-control" placeholder="Usuario" id="loginUsuario">
                        </div>
                        <div class="form-group">
                            <label for="login_con">Contraseña:</label>
                            <input type="text" name="txtContraseña" class="form-control" placeholder="Contraseña" id="loginContrasena">
                        </div>
                        <div class="form-group">
                            <button type="button" class="btn btn-primary" id="btnAceptar" onclick="login()">Aceptar</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
<footer class="card-footer bg-dark text-white text-center ">Copyright 2017</footer>
<script src="js/ajax/ajaxlogin.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.bundle.js"></script>
<script src="js/jquery-3.2.1.js"></script>
</body>
</html>

consultas.php

<?php
include("bd/conexionbd.php");
$usuario=$_POST['Usuario'];
$contrasena=$_POST['Password'];

$cmd= $conn->prepare('SELECT usuario, rol_usuario.nombre_Rol FROM usuario inner join rol_usuario on usuario.id_Rol=rol_usuario.id_Rol where Usuario=? AND Contrasena=?');
$cmd->bind_param('ss',$nom_usuario, $usuario_cont);
$nom_usuario=$usuario;
$usuario_cont=md5($contrasena);
$cmd->execute();

/*Se vincula 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) {
echo'hay resultados';
$cmd->fetch();
echo "$user"." ".$rol;
}else{
echo 'no hay resultados';
}

?>

ajaxlogin.js

function login(){
if ($('#loginUsuario').val()===""|| $('#loginContrasena').val()==="") {
    $('#warning-div').css({
        'display': 'block'
    }); 
    $('#warning-div').addClass('row bg-danger justify-content-center text-center');
    $('#warning-text').addClass('text-white');
    document.getElementById('warning-text').innerHTML='Hay Campos Vacios';  
}else{

    var usuario= $('#loginUsuario').val();
    var password =$('#loginContrasena').val();

        ajaxLogin(usuario,password);

    }
}

function ajaxLogin(usuario,password){
alert('Entraste al ajax');

$.ajax({
    url: '../../php/consultas.php',
    type: 'POST',
    dataType: 'html',
    data: "Usuario="+usuario+"&Password="+password,
    beforeSend: function(){
        $('#warning-div').css({
        'display': 'block'
    }); 
    $('#warning-div').addClass('row bg-warning justify-content-center text-center');
    $('#warning-text').addClass('text-white');
    document.getElementById('warning-text').innerHTML='Iniciando Sesión...';    
    },
})
.done(function() {
    console.log("success");
})
.fail(function() {
    console.log('Error');   })
.always(function() {
    console.log("complete");
});


}

The idea is: Get the two columns of the consulta MySQL using the ajax() function and redirect according to the value of the Role column (user or administrator). The problem is that the ajax does not work.

    
asked by Ferny Cortez 07.11.2017 в 21:51
source

1 answer

1

I've tried your code and it's almost okay, except for a few things:

The done needs to receive the parameter of what it gets from the server:

.done(function(data) {  ...

and you can do a test of what you are returning:

console.log(data);

The ajaxLogin function would look like this:

function ajaxLogin(usuario,password){
alert('Entraste al ajax');

$.ajax({
    url: 'ok.php',
    type: 'POST',
    dataType: 'html',
    data: "Usuario="+usuario+"&Password="+password,
    beforeSend: function(){
        $('#warning-div').css({
        'display': 'block'
    }); 
    $('#warning-div').addClass('row bg-warning justify-content-center text-center');
    $('#warning-text').addClass('text-white');
    document.getElementById('warning-text').innerHTML='Iniciando Sesión...';    
    },
})
.done(function(data) {
    console.log(data);
})
.fail(function() {
    console.log('Error');   })
.always(function() {
    console.log("complete");
});


}

Notes:

For this to work I made sure that:

  • The PHP file that calls ajax works properly
  • The path of that file is correct
  • The jQuery library is properly loaded

I would put all my jQuery functions within function , so they do not try to run before the DOM is ready.

    
answered by 08.11.2017 / 00:17
source