duanbu1421 2017-05-29 17:37
浏览 45

查询数据库时,PHP + AJAX不会产生结果

I'm taking my first steps in PHP and now I'm trying to create a simple login form and trying to validate the information using AJAX and PHP by querying a database. I used Ajax because I needed to change a few elements on my page in case the login information wasn't valid and later I found out that you can't actually call a php function directly from jquery, you need to use ajax instead. I have this form in a php file:

  <body>
    <div class="wrapper" id="mainWrapper" style="display:none;">
      <img src="assets/icons/user.png" id="userLogo" alt="user-icon">
      <form>
      <div class="form-div">
        <input type="text" required id="username" name="user" placeholder="Username">
      </div>
      <div class="form-div">
        <input type="password" required id="password" name="pass" placeholder="Password">
      </div>
      <input type="button" name="submit" id="loginButton" value="login" onclick="post();" class="btn-login">
      </form>
      <br>
      <a href="recover.php">Forgot password?</a>
      <br>
      <div id="status"></div>
      </div>
    </div>
  </body>

And I've created this ajax script to send my variables to the php file that is supposed to test the login information, this is the ajax script:

    <script type="text/javascript">
      function post() {

   var hr = new XMLHttpRequest();
   // Create some variables we need to send to our PHP file
   var url = "testLogin.php";
   var username = document.getElementById("username").value;
   var password = document.getElementById("password").value;
   var vars = "username="+username+"&password="+password;
   hr.open("POST", url, true);
   // Set content type header information for sending url encoded variables in the request
   hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   // Access the onreadystatechange event for the XMLHttpRequest object
   hr.onreadystatechange = function() {
     if(hr.readyState == 4 && hr.status == 200) {
       var return_data = hr.responseText;

    if(return_data == "false")
    {
      document.getElementById('userLogo').style.display = "none";
      document.getElementById('userLogo').src = "assets/icons/error.png";
      $("#userLogo").fadeIn(1000);
      document.getElementById('status').innerHTML = "Username ou password inválidos";
    }
    else
    {
      document.getElementById('userLogo').style.display = "none";
      document.getElementById('userLogo').src = "assets/icons/user.png";
      document.getElementById('status').innerHTML = "";
      $("#userLogo").fadeIn(1000);
    }
     }
   }
   // Send the data to PHP now... and wait for response to update the status div
   hr.send(vars); // Actually execute the request
   document.getElementById("status").style.visibility = "a processar...";

      }
    </script>

I get the value of the password and username by accessing the elements via their ID and then I send it to the php file entitled "testLogin.php" that contains the script to test the login information this is the content of that file:

<?php
session_start();
include_once('connect.php');
if(isset($_POST['username']))
{
  $username = $_POST['username'];
  $password = $_POST['password'];
  $sql = "SELECT * FROM users WHERE Username = '".$username."' AND password ='".$password."' LIMIT 1";
  $result = mysql_query($sql) or die(mysql_error());
  if(mysql_num_rows($result) == 1)
  {
      $row = mysql_fetch_assoc($result);
      echo "true";
      exit();
  }
}
  else
  {
    echo "false";
    exit();
}
?>

Im the ajax scrip previously shown I'm "listening" for a echo of true if the information is correct and an echo of false if the information is not valid. When I change the code in the test script to this:

if($_POST['username'] == 'Joao' && $_POST['password'] == "meu")
echo "true";
else echo "false";

it works perfectly, because of this I have in mind that maybe there is an error with either ajax calling the php file or something to do with php querying the database, and I can't tell because I feel powerless testing this. I would appreciate if anyone could give me a help to figure out if it's the connection to the database or something to due with ajax or php. Thank you

EDIT: This is the content of the connection file

<?php
$host = "localhost";
$username = "root";
$password = "";
$db = "forum";
mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($db);
 ?>

I've now changed all the deprecated mysql functions to mysqli as suggested:

<?php
session_start();
include_once("config.php")
if(isset($_POST['username']) && isset($_POST['password']))
{

$status = "";
$username = $_POST['username'];
$password = $_POST['password'];
  if($bd = mysqli_connect('localhost','root','','forum'))
  {
     if($command = mysqli_prepare($bd,"SELECT *  FROM users WHERE Username = ? AND password = ? "))
     {
       mysqli_stmt_bind_param($command,"ss",$username,$password);
       mysqli_stmt_execute($command);
       mysqli_stmt_bind_result($command,$testUser,$testPass);
       mysqli_stmt_fetch($command);
       if($username == $testUser && $password == $testPass)
       $status = "true";
       else $status = "false";
       mysqli_stmt_close($command);
     }
    mysqli_close($bd);

  }

}
else $status = "false";

echo $status;
exit();

But I still get the same result

  • 写回答

2条回答 默认 最新

  • dongzhong9055 2017-05-29 18:44
    关注

    Your tons of code could be simplified by using jquery ajax call. For example:

    $.ajax({
    type: "POST",
    url: url,
    data: data,
    success: success,
    dataType: dataType
    });
    

    For details refer jquery ajax manual it's very simple. In the php script:

    • Please use PDO in php for code security.
    • What is the need for mysql_fetch_assoc () when you don't want to see any data.
    • Besides, selecting rows only to count them simply makes no sense. A count(*) query have to be run instead, with only one row returned.
    • the if statement is returning true and what if it is false. So a else statement is also required. Your else is returning false only when username is not set.
    • Also session_start() has no use in your script.

    Hope it helps you understand.

    Update:

    Problem1: How to validate the form?

    Solution: See this example:

        $(document).ready(function(){
         $('#form_id').on('submit',function(e){
            var username = $('#username').val();
            var password = $('#password').val();
    
           if(username == '' || password == '')
          {
          alert('required fields!!');
          e.preventDefault(); //stop submitting the form.
          }else{
    
         //here your ajax call
    
         }
       });
    
    });
    

    Problem2: How to use serialize in form submit?

    Solution: in jquery do it like this

       $('#form').serialize(); //use in your ajax call
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大