使用jquery和php登录Ajax [英] Ajax login using jquery and php

查看:72
本文介绍了使用jquery和php登录Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关登录系统的帮助.

我正在关注本教程: http://tutsforweb.blogspot.pt /2012/05/ajax-login-form-with-jquery-and-php.html

一切正常,完全符合我登录系统的要求,但如果用户名和密码正确,则仅进行登录,并在以下情况下显示错误的用户名或密码"消息:

  • 字段为空
  • 用户名不存在
  • 密码错误

我想让每种情况下显示不同的消息

有人可以告诉我该怎么做吗?请理解,我了解0的ajax和jquery.

这是index.php的代码

<script type="text/javascript">
$(document).ready(function(){
    $("#login_a").click(function(){
        $("#shadow").fadeIn("normal");
         $("#login_form").fadeIn("normal");
         $("#user_name").focus();
    });
    $("#cancel_hide").click(function(){
        $("#login_form").fadeOut("normal");
        $("#shadow").fadeOut();
   });
   $("#login").click(function(){

        username=$("#user_name").val();
        password=$("#password").val();
         $.ajax({
            type: "POST",
            url: "login.php",
            data: "name="+username+"&pwd="+password,
            success: function(html){
              if(html=='true')
              {
                $("#login_form").fadeOut("normal");
                        $("#shadow").fadeOut();
                        $("#profile").html("<a href='logout.php' id='logout'>Logout</a>");

              }
              else
              {
                    $("#add_err").html("Wrong username or password");
              }
            },
            beforeSend:function()
            {
                 $("#add_err").html("Loading...")
            }
        });
         return false;
    });
});
</script>
</head>
<body>
    <div id="profile">
    <a id="login_a" href="#">login</a>
    </div>
    <div id="login_form">
        <div class="err" id="add_err"></div>
        <form action="login.php">
            <label>User Name:</label>
            <input type="text" id="user_name" name="user_name" />
            <label>Password:</label>
            <input type="password" id="password" name="password" />
            <label></label><br/>
            <input type="submit" id="login" value="Login" />
            <input type="button" id="cancel_hide" value="Cancel" />
        </form>
    </div>
    <div id="shadow" class="popup"></div>
</body>

这是login.php的代码

<?php
session_start();
$username = $_POST['name'];
$password = $_POST['pwd'];
$mysqli=mysqli_connect('localhost','root','','logintest');

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
        $row=mysqli_fetch_array($result);
        if( $num_row >=1 ) {
            echo 'true';
            $_SESSION['user_name']=$row['username'];
        }
        else{
            echo 'false';
        }
?>

PS:我还有其他话题,我编辑过一些奇怪的代码,但是我认为这更具体地说明了我的问题和我想要的是什么.

如果有人能帮助我,我会很感激.

解决方案

在您要实现的功能范围内,我认为您只想处理PHP中的所有3个附加条件(尽管字段的第一个条件是可以使用jQuery检查是否为空),但是为了保持整洁,您可以使用PHP测试所有条件,并从php返回将由jQuery处理的不同情况.

通过查看以下代码行,可以使您了解ajax和jquery在这里的工作方式:

$.ajax({
        type: "POST",
        url: "login.php",
        data: "name="+username+"&pwd="+password,
        success: function(html){

ajax方法通过在该文件上发布数据来调用login.php文件. PHP返回或回显的所有内容都将通过参数'html'在成功函数中获取.请注意,"html"只是在此处使用的变量名,尽管实际上仅会在此处获取字符串.

例如在php中,如果登录成功,则返回"true",并在成功函数的html变量中提取相同的文本.条件if(html =='true')只是检查并隐藏表单.

一种实现目标的方法是为每种情况从PHP定义不同的返回值,可以是: 1:登录成功 2:其中一个字段(用户名或密码)为空 3:用户名不存在 4:密码错误

PHP代码将如下所示:

    <?php
        session_start();
        $username = $_POST['name'];
        $password = $_POST['pwd'];
        // Check if any of the fields is empty
        if(empty($username) || empty($password)){
            echo '2';
        } else {
            $mysqli=mysqli_connect('localhost','root','','logintest');

            // Check if username exists
            $query = "SELECT * FROM users WHERE username='$username'";
            $result = mysqli_query($mysqli,$query)or die(mysqli_error());
            $num_row = mysqli_num_rows($result);
            if($num_row == 0){
                echo '3';
            } else {
                $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
                $result = mysqli_query($mysqli,$query)or die(mysqli_error());
                $num_row = mysqli_num_rows($result);
                $row=mysqli_fetch_array($result);
                if( $num_row >=1 ) {
                    echo '1';
                    $_SESSION['user_name']=$row['username'];
                }
                else{
                    echo '4';
                }
            }
        }
?>

现在,这些返回值可以在jQuery中使用switch语句进行处理

success: function(html){
              switch(html)
              {

                case '1': // Login successful 
                        $("#login_form").fadeOut("normal");
                        $("#shadow").fadeOut();
                        $("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
                        break;

                case '2': // Empty Field
                    $("#add_err").html("Please fill both username and password");
                        break;
                case '3': // username doesn't exist
                        $("#add_err").html("Username doesn't exist");
                        break;
                case '4': //Password is wrong
                        $("#add_err").html("Password is wrong");
                        break;
            }
        }

我希望这会帮助您获得想要的东西

I need some help with the login system.

Im following this tutorial: http://tutsforweb.blogspot.pt/2012/05/ajax-login-form-with-jquery-and-php.html

Everything works fine and its exactly what I want for my login system, but instead of only make login if the username and password are correct and displaying the message "Wrong username or password" if:

  • the fields are empty
  • username doesnt exist
  • password is wrong

I wold like to make it to display a diferent message for each one of cases

Can someone tell me how to do that? Pls, I understand 0 of ajax and jquery.

This is the code of index.php

<script type="text/javascript">
$(document).ready(function(){
    $("#login_a").click(function(){
        $("#shadow").fadeIn("normal");
         $("#login_form").fadeIn("normal");
         $("#user_name").focus();
    });
    $("#cancel_hide").click(function(){
        $("#login_form").fadeOut("normal");
        $("#shadow").fadeOut();
   });
   $("#login").click(function(){

        username=$("#user_name").val();
        password=$("#password").val();
         $.ajax({
            type: "POST",
            url: "login.php",
            data: "name="+username+"&pwd="+password,
            success: function(html){
              if(html=='true')
              {
                $("#login_form").fadeOut("normal");
                        $("#shadow").fadeOut();
                        $("#profile").html("<a href='logout.php' id='logout'>Logout</a>");

              }
              else
              {
                    $("#add_err").html("Wrong username or password");
              }
            },
            beforeSend:function()
            {
                 $("#add_err").html("Loading...")
            }
        });
         return false;
    });
});
</script>
</head>
<body>
    <div id="profile">
    <a id="login_a" href="#">login</a>
    </div>
    <div id="login_form">
        <div class="err" id="add_err"></div>
        <form action="login.php">
            <label>User Name:</label>
            <input type="text" id="user_name" name="user_name" />
            <label>Password:</label>
            <input type="password" id="password" name="password" />
            <label></label><br/>
            <input type="submit" id="login" value="Login" />
            <input type="button" id="cancel_hide" value="Cancel" />
        </form>
    </div>
    <div id="shadow" class="popup"></div>
</body>

And this is the code of login.php

<?php
session_start();
$username = $_POST['name'];
$password = $_POST['pwd'];
$mysqli=mysqli_connect('localhost','root','','logintest');

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
        $row=mysqli_fetch_array($result);
        if( $num_row >=1 ) {
            echo 'true';
            $_SESSION['user_name']=$row['username'];
        }
        else{
            echo 'false';
        }
?>

PS: I had other topic with some wierd code edited by me, but I think this is more expecific of what Is my problem and what I want.

If someone could help me I appreciate that.

解决方案

Within the scope of functionality you are trying to achieve, I think you would want to handle all the 3 additional conditions from PHP only (though first condition of fields being empty can be checked using jQuery) but to keep it clean, you can test all the conditions using PHP and return different cases from php that will be accordingly handled by jQuery.

To give you understanding of how ajax and jquery are working here, looking at these lines of code:

$.ajax({
        type: "POST",
        url: "login.php",
        data: "name="+username+"&pwd="+password,
        success: function(html){

The ajax methods call the login.php file by POSTing data on it. Whatever is returned or echoed by PHP will be fetched in the success function through the parameter 'html'. Note that 'html' is just a variable name being used here though actually just a string will be fetched here.

E.g. In the php, if login is successful 'true' is echoed and the same text is fetched in html variable in the success function. The condition if(html=='true') just checks that and hides the form.

One way to achieve your objective is you define different return values for each case from PHP which can be: 1: Login successful 2: One of the fields (username or password) are empty 3: Username doesn't exist 4: Password is wrong

For which the PHP code will be like this:

    <?php
        session_start();
        $username = $_POST['name'];
        $password = $_POST['pwd'];
        // Check if any of the fields is empty
        if(empty($username) || empty($password)){
            echo '2';
        } else {
            $mysqli=mysqli_connect('localhost','root','','logintest');

            // Check if username exists
            $query = "SELECT * FROM users WHERE username='$username'";
            $result = mysqli_query($mysqli,$query)or die(mysqli_error());
            $num_row = mysqli_num_rows($result);
            if($num_row == 0){
                echo '3';
            } else {
                $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
                $result = mysqli_query($mysqli,$query)or die(mysqli_error());
                $num_row = mysqli_num_rows($result);
                $row=mysqli_fetch_array($result);
                if( $num_row >=1 ) {
                    echo '1';
                    $_SESSION['user_name']=$row['username'];
                }
                else{
                    echo '4';
                }
            }
        }
?>

Now, these returns values can be handled in jQuery with switch statement

success: function(html){
              switch(html)
              {

                case '1': // Login successful 
                        $("#login_form").fadeOut("normal");
                        $("#shadow").fadeOut();
                        $("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
                        break;

                case '2': // Empty Field
                    $("#add_err").html("Please fill both username and password");
                        break;
                case '3': // username doesn't exist
                        $("#add_err").html("Username doesn't exist");
                        break;
                case '4': //Password is wrong
                        $("#add_err").html("Password is wrong");
                        break;
            }
        }

I hope this will help you getting what you want

这篇关于使用jquery和php登录Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆