weixin_33730836 2017-08-06 11:03 采纳率: 0%
浏览 21

Ajax成功对象

I'm trying to validate the form using AJAX. This is what I've done so far:

$('#login-form').submit(function(e) {
  e.preventDefault();
  var user = username.value;
  var pass = password.value;

  if (user != '' && pass != '') {
    $('#login').html('Proccessing...');
    $.ajax({
      url: 'login.php',
      type: 'POST',
      data: {
        username: user,
        password: pass
      },
      processData: false,
      contentType: false,
      success: function(response) {
        if (response == 'success') {
          window.location.href = 'admin.php';
        } else {
          $('.login_message').html('Incorrect Credentails');
          $('#login').html('Login');
        }
      }
    });
  } else {
    $('.login_message').html('Fill All Fields');
    $('#login').html('Login');
  }
})

and it seems like response doesn't return success. Below is the login.php file

<?php
session_start();
$password = $username = '';
$_SESSION['user'] = $_SESSION['error'] = '';


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['login'])) {
        include_once('db.php');
        $username = strip_tags($_POST['username']);
        $password = strip_tags($_POST['password']);

        $password = md5($password);
        echo 'username: ' . $username . ' and ' . ' password: ' . $password;
        $sql   = "select * from users where username = '" . $username . "' limit 1";
        $query = mysql_query($sql);

        if ($query) {
            $row    = mysql_fetch_assoc($query);
            $dbpass = $row['password'];
            if ($password == $dbpass) {
                ;
                $_SESSION['user'] = $username;
                header('Location: admin.php');
            } else {
                $_SESSION['error'] = 'Wrong username or password!';
            }
        } else {
            echo mysql_error();
        }
    }
}
?>

If it happens you have found the solution, please explain to me how you find the solution and what I've done wrong. Thank you in advance.

  • 写回答

2条回答 默认 最新

  • 旧行李 2017-08-06 11:24
    关注

    Returning values from PHP back to JS

    When using AJAX, I believe if you do echo in the PHP target file (here login.php) it will act as a return. Therefore the code after a echo will not run as you might expect.

    Also in your code you have: echo $_SESSION['error'] = '';

    Use == to compare two object, = is the assignment operator.


    Retrieving AJAX data in PHP file

    The use of the ajax() method from jQuery in your code looks correct to me. So when the call is made the information is sent asynchronously to the server. More precisely it will send the parameters to the PHP file you've specified in the ajax object properties: login.php.

    In login.php you can access your passed parameters in the $_POST array.

    You would have the following:

    $username = $_POST['username'];
    $password = $_POST['password'];
    
    // process information...
    $state = 'success'
    
    // now you can return a JSON object back to your page
    // I strongly recommend using a PHP array and converting it to JSON
    // this way it's very easy to access it back with JS
    
    $response = array(state=$state)
    echo json_encode($response);
    

    And back in your jQuery code you access the state value with response.state

    if(response.state == 'success') {
      alert('It is a succcess!');
    }
    

    Debugging PHP target files

    Now you generally have problems in the code in this PHP files. And it's not an easy thing to debug it. So the way I proceed is: I set the parameters in stone in login.php for instance:

    $username = 'usernameTest'; // $username = $_POST['username'];
    $password = 'passwordTest'; // $password = $_POST['password'];
    

    Then I would open the PHP file in a browser and run it do see if it echoes the object and if there are any bugs.

    Then you can put back $username = $_POST['username']; and $password = $_POST['password'];.


    Actual code

    <?php
    session_start();
    
    if (isset($_POST['username'], $_POST['password']) {
        include_once('db.php');
    
        $username = strip_tags($_POST['username']);
    
        $password = strip_tags($_POST['password']);
        $password = md5($password);
    
        $sql   = "select * from users where username = '" . $username . "' limit 1";
        $query = mysql_query($sql);
    
        if ($query) {
          $row = mysql_fetch_assoc($query);
          $dbpass = $row['password'];
    
            if ($password == $dbpass) {
               $state = 'success';
            } else {
               $state = 'failed';
            }
    
        } else {
          echo mysql_error();
        }
    }
    

    Warning mysql(), md5() and SQL injections

    • Don't use the deprecated and insecure mysql_* functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7 (in 2015). Use MySQLi or PDO instead.

    • You are wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Using strip_tags() is far from a safe way to escape data.

    • Don't use md5() for password hashing. It's very insecure. Use PHP's password_hash() and password_verify() instead. If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality.

    - Magnus Eriksson

    评论

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛