2017-05-29 81 views
1

我正在开始使用PHP的第一步,现在我试图创建一个简单的登录表单并试图通过查询数据库来验证使用AJAX和PHP的信息。 我使用Ajax是因为我需要更改页面上的一些元素,以防登录信息无效,后来发现您无法直接从jquery调用php函数,而是需要使用ajax。 我有这种形式的PHP文件:查询数据库时PHP + AJAX不产生结果

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

而且我创造了这个AJAX脚本,我的变量发送到应该测试登录信息php文件,这是AJAX脚本:

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

我通过通过其ID访问的元素得到了用户名和密码的值,然后我把它发送到包含脚本来测试登录信息 题为“testLogin.php” php文件,这是内容该文件:

<?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先前显示的ajax脚本如果信息正确,我正在“听”回声为真,如果信息无效,则回声为假。 当我更改了测试脚本此代码:

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

它完美的作品,因为这个我心目中,也许没有与任何AJAX调用PHP文件或者是与PHP的错误查询数据库,我无法分辨,因为我感觉无力测试它。 我将不胜感激,如果任何人都可以给我一个帮助,找出它是否连接到数据库或由于使用ajax或PHP。 谢谢

编辑:这是连接文件的内容

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

我现在已经改变了所有的弃用MySQL的函数库MySQLi的建议:

<?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(); 

但我仍然得到相同的结果

+1

许多mysql方法已被弃用,您应该查看mysqli或PDO进行数据库访问。 –

+0

@NigelRen可能是我面临的问题的原因吗? – KingOFNewbies

+0

@NigelRen'mysql_'方法*此外,所有这些都被弃用,并从php7中完全删除。 @Newbies,你使用的是什么版本的PHP? – Terminus

回答

0

Your tons of代码可以通过使用jquery ajax调用来简化。例如:

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

有关详细信息,请参阅jquery ajax手册,它非常简单。 在php脚本中:

  • 请在php中使用PDO代码安全性。
  • 当你不想看到任何数据时,需要mysql_fetch_assoc()什么。
  • 此外,选择行来计算它们根本没有意义。必须运行count(*)查询,而只返回一行。
  • if语句返回true,如果为false,该怎么办?所以还需要一个else语句。只有在未设置用户名时,您的其他人才会返回false。
  • 另外session_start()在脚本中没有用处。

希望它能帮助你理解。

更新:

问题1:如何验证表单?

答:请参阅下面的例子:

$(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:如何使用序列化的形式提交?

解决方案:jQuery的做这样的

$('#form').serialize(); //use in your ajax call 
+0

我现在试图使用该ajax后,我已经拿出取和使用计数(*)来代替。 – KingOFNewbies

+0

在你回答和搜索后,我终于找到了一些与你的ajax例子一起工作的东西,检查我的答案,并告诉我是否有问题或者我可以改变 – KingOFNewbies

1

好几个小时的研究后,通过文件和所有的阅读,并与你的问题的宝贵帮助,我得到这个代码,实际工作。 我已经改变了Ajax调用:

<script> 
function confirmar() 
{ 
    var username = $("#username").val(); 
    var password = $("#password").val(); 
    $.ajax({ 
    //The file containing the script to test the login information 
    url: "testLogin.php", 
    //The type of the call (POST, GET) 
    type: "POST", 
    //the information to be tested, send it through the URL (form serialization may be a better choice than this aproach) 
    data: "username="+username+"&password="+password 
    }).done(function(resp) 
    { 
    //the server response stating that the test was a failure 
    if(resp == "notok") 
    { 
     $('#loader').hide(); 
     $("#loginButton").show(); 
     $('#userLogo').css('display',"none"); 
     $('#userLogo').attr('src',"assets/icons/error.png"); 
     $("#userLogo").fadeIn(1000); 
     $('#status').html("Username ou password inválidos"); 
     return; 
    } 
    else 
    { 
     $('#loader').show(); 
     $("#loginButton").show(); 
     $('#userLogo').css('display',"none"); 
     $('#userLogo').attr('src',"assets/icons/user.png"); 
     $('#status').html(""); 
     $("#userLogo").fadeIn(1000); 
     window.location = "userDetails.php"; 
    } 
    }) 
} 
    </script> 

这在我看来,是比我更具可读性,我觉得它更容易理解为好。 后,我明白了Ajax调用实际上是如何工作的我去改变从数据库中获取数据的php文件,实际上它测试此:

<?php 
if(isset($_POST['username']) && isset($_POST['password'])) 
{ 
$username = $_POST['username']; 
$password = $_POST['password']; 
if($username == "" || $password == "") 
{ 
    //server response if the info or the test wasnt valid 
    echo "notok"; 
    exit(); 
} 
} 
else 
{ 
    echo "notok"; 
    exit(); 
} 
if($bd = mysqli_connect("localhost", "root", "", "forum")) 
{ 
    if($stmt = mysqli_prepare($bd, 
    "SELECT User_ID, username, password, email from users WHERE Username = '".$username."'")) { 
    mysqli_stmt_execute($stmt); 
    mysqli_stmt_bind_result($stmt, $idUser, $name, $pass, $email); 
    mysqli_stmt_fetch($stmt); 
    if($name == $username && $password == $pass) echo "ok"; 
    else echo "notok"; 
    mysqli_stmt_close($stmt); 
    } 
    mysqli_close($bd); 
    } 
?> 

这实际上产生的结果我是后。 我只有3个问题atm问题。 第一个是在调用ajax的jquery函数中,我认为这是测试用户名和密码字段是否为空的最佳位置。我加入这个代码行这样做:

if(password == "" || username ||) 
    { 
    alert("please fill out the information required for the login"); 
    return; 
    } 

,但补充说,代码Ajax调用不再工作之后...... 的第二件事情是,我找到事做形式序列化ajax调用我认为比通过元素ID获取值要精确得多,我没有得到这个工作。

+0

我已经编辑了我的答案检查它。希望它能更多地澄清你。 – CoderSam