简体   繁体   English

允许登录表单在不刷新页面的情况下处理同一页面上的php脚本

[英]Allow a login form to process php script on same page without refreshing the page

EDIT 编辑
Thanks to, Wes CI now have this AJAX Code: 多亏了,Wes CI现在有了这个AJAX代码:

   <script type="text/javascript"> 
$(document).ready(function(){
    $("form[name^='login']").submit(function(event) {
        event.preventDefault();

        var dataToSend = 'username='+$("input[name^='username']").val()+'&password='+$("input[name^='password']").val();

        $.ajax({
            type: "POST",
            url: "index.php",
            data: dataToSend,
            success: function(response){
                if(response == "REDIRECT")
                {
                    window.location = "business_profiles/myReviews.php";
                else
                {
                    $("#my_error_div").html(response);
                }
            }
        });
    });
});
</script>

But now instead of showing the error messages when you for instance type your password box. 但是,现在,例如在键入密码框时不再显示错误消息。 All I receive is an alert box saying "Success" regardless of what the forms input is. 我收到的只是一个警告框,上面写着“成功”,而不管输入的表单是什么。

Ok, I have tried and tried to figure this out on my own. 好的,我尝试并尝试自行解决。 As well as reached out to fellow coders and of course searched stackoverflow for answers. 以及与其他编码人员的联系,当然还要在stackoverflow上搜索答案。 None really seemed to match my situation. 似乎没有一个真的符合我的情况。

I have a simple login form like so: 我有一个简单的登录表单,如下所示:

<form name="login" action="index.php" method="post">

        <ul>

            <li>
                <input type="text" name="username" autocomplete="off" placeholder="Username" autofocus="true"></li>

            <li>
                <input type="password" name="password" autocomplete="off" placeholder="Password"></li>
            <li>

                <input type="submit" name="submit" value="Login"> <a href="register.php" id="button">Register</a> <a href="forgot.php" id="button">Forgot Password</a> <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'" id="button">Close</a>

            </li>
        </ul>
    </form>

This form submits to the same page that it is on. 该表格将提交到与之相同的页面。 (the php script is right above the login form.) and that is as follows: (php脚本位于登录表单的上方。)如下所示:

    <?php

//If the user has submitted the form
if($_POST['username']){
    //protect the posted value then store them to variables
    $username = protect($_POST['username']);
    $password = protect($_POST['password']);

    //Check if the username or password boxes were not filled in
    if(!$username || !$password){
        //if not display an error message
        echo "<center>You need to fill in a <b>Username</b> and a <b>Password</b>!</center>";
    }else{
        //if the were continue checking

        //select all rows from the table where the username matches the one entered by the user
        $res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."'");
        $num = mysql_num_rows($res);

        //check if there was not a match
        if($num == 0){
            //if not display an error message
            echo "<center>The <b>Username</b> you supplied does not exist!</center>";
        }else{
            //if there was a match continue checking

            //select all rows where the username and password match the ones submitted by the user
            $res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
            $num = mysql_num_rows($res);

            //check if there was not a match
            if($num == 0){
                //if not display error message
                echo "<center>The <b>Password</b> you supplied does not match the one for that username!</center>";
            }else{
                //if there was continue checking

                //split all fields fom the correct row into an associative array
                $row = mysql_fetch_assoc($res);

                //check to see if the user has not activated their account yet
                if($row['active'] != 1){
                    //if not display error message
                    echo "<center>You have not yet <b>Activated</b> your account!</center>";
                }else{
                    //if they have log them in

                    //set the login session storing there id - we use this to see if they are logged in or not
                    $_SESSION['uid'] = $row['id'];
                    //show message
                    echo "<center>You have successfully logged in!</center>";

                    //update the online field to 50 seconds into the future
                    $time = date('U')+50;
                    mysql_query("UPDATE `users` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");

                    //redirect them to the usersonline page
                    echo 'REDIRECT';

                    exit;
                }
            }
        }
    }
}

?>

I am needing the form to process the script WITHOUT refreshing the page. 我需要表单来处理脚本而无需刷新页面。 My Login form is within a light box so in turn if there is an error like an invalid password when the page refreshes the light box hides again and you have to click Login again to find out what you did wrong. 我的登录表单位于一个灯箱中,因此,如果在页面刷新时出现错误(例如密码无效),则会再次隐藏灯箱,您必须再次单击“登录”以找出您做错了什么。 I just want the form to process the php script without refreshing the page so the light box never hides until the user has logged in successfully. 我只希望表单在不刷新页面的情况下处理php脚本,因此灯箱永远不会隐藏,直到用户成功登录为止。 Which then the user is redirected to their profile. 然后将用户重定向到他们的个人资料。

Using jQuery, you could post the data from the login form to the same page using the following AJAX function: 使用jQuery,您可以使用以下AJAX函数将数据从登录表单发布到同一页面:

<script type="text/javascript"> 
$(document).ready(function(){
    $("form[name^='login']").submit(function(event) {
        event.preventDefault();

        var dataToSend = 'username='+$("input[name^='username']").val()+'&password='+$("input[name^='password']").val();

        $.ajax({
            type: "POST",
            url: "index.php",
            data: dataToSend,
            success: function(response){
                if(response == "REDIRECT")
                {
                    window.location = "business_profiles/myReviews.php";
                }
                else
                {
                    alert("Error: "+response);
                    $("#my_error_div").html(response);
                }
            }
        });
    });
});
</script>

Also, change your PHP to: 另外,将您的PHP更改为:

<?php

//If the user has submitted the form
if(isset($_REQUEST['username'])){
    //protect the posted value then store them to variables
    $username = protect($_POST['username']);
    $password = protect($_POST['password']);

    //Check if the username or password boxes were not filled in
    if(!$username || !$password){
        //if not display an error message
        echo "<center>You need to fill in a <b>Username</b> and a <b>Password</b>!</center>";
    }else{
        //if the were continue checking

        //select all rows from the table where the username matches the one entered by the user
        $res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."'");
        $num = mysql_num_rows($res);

        //check if there was not a match
        if($num == 0){
            //if not display an error message
            echo "<center>The <b>Username</b> you supplied does not exist!</center>";
        }else{
            //if there was a match continue checking

            //select all rows where the username and password match the ones submitted by the user
            $res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
            $num = mysql_num_rows($res);

            //check if there was not a match
            if($num == 0){
                //if not display error message
                echo "<center>The <b>Password</b> you supplied does not match the one for that username!</center>";
            }else{
                //if there was continue checking

                //split all fields fom the correct row into an associative array
                $row = mysql_fetch_assoc($res);

                //check to see if the user has not activated their account yet
                if($row['active'] != 1){
                    //if not display error message
                    echo "<center>You have not yet <b>Activated</b> your account!</center>";
                }else{
                    //if they have log them in

                    //set the login session storing there id - we use this to see if they are logged in or not
                    $_SESSION['uid'] = $row['id'];


                    //update the online field to 50 seconds into the future
                    $time = date('U')+50;
                    mysql_query("UPDATE `users` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");

                    //redirect them to the usersonline page
                    echo 'REDIRECT';
                }
            }
        }
    }

    exit;
}

?>

step1:Add a div to your login form. 步骤1:将div添加到您的登录表单中。

step2: Validate the user controls and then load the page in the ajax call 步骤2:验证用户控件,然后在ajax调用中加载页面

step3:In the ajax success event append the page you want to show using .html() 第三步:在ajax成功事件中,使用.html()附加要显示的页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM