在Ajax Call

时间:2016-03-15 21:45:48

标签: javascript php jquery ajax

我正在尝试使用php,jquery,ajax,json创建一个登录系统,它验证是否有空字段,但是一旦我完成并提交表单,ajax调用失败,控制台显示json数组在响应文本中,所以问题不在于php部分,但是它说parsererror,我不知道如何解决这个问题,我还是一个菜鸟。这是我的代码:

的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;

});

我在控制台中收到以下错误:

  

ajax.js:53:Object {readyState:4,responseText:   “{”失败“:真实的,”消息“:”厄尔尼诺   usuario aa no existe(用户aa不存在)&lt; / div&gt;“}”,状态:   200,statusText:“OK”} ajax.js:54:parsererror

That's what the console shows, i don't know how to get the http headers :(

我从控制台得到了这个:

SyntaxError:意外的令牌     at Object.parse(native)     在n.parseJSON(http://localhost/ajax/js/jquery2.js:4:6225)     在zb(http://localhost/ajax/js/jquery2.js:4:8172)     在z(http://localhost/ajax/js/jquery2.js:4:11629)     在XMLHttpRequest。 (http://localhost/ajax/js/jquery2.js:4:15507

似乎我收到了一个格式错误的请求,这就是我在另一个问题中读到的内容

1 个答案:

答案 0 :(得分:0)

看起来你正在点击ajax.js第54行的error()回调和解析错误:

console.log(textStatus);

我们需要进入您的success回调。返回浏览器的HTTP状态代码是什么?您可以使用Chrome工具或Firebug查找,并在浏览器中查看响应。

您的回复JSON正文看起来像这样: { "fail": true, "messages": "El usuario aa no existe(the user aa doesn´t exist)</div>" }

messages包含El usuario aa no existe(the user aa doesn´t exist)</div> - 实际上是一个尾随</div>,没有开放<div>

重要的旁注:看起来您正在从请求值中获取原始用户输入并在此语句中通过数据库运行它:"Select * from user where username = '{$user}'"。这使您可以使用SQL Injection attack。恶意攻击者可以使用它来删除数据库中的数据或选择您不希望暴露的数据。您应该切换到使用PDO + prepared statements或转义输入数据以防止这种情况。