简体   繁体   English

登录后如何保持在同一页面上

[英]How to stay on same page after login

I am building an event registration system which displays event registration list if the user is logged in without page refresh using Ajax. 我正在构建一个事件注册系统,如果用户使用Ajax登录时没有页面刷新,它会显示事件注册列表。 However, when I try to login I get undefined index name on line echo "Hello ".$_SESSION["name"]."<br/>"; 但是,当我尝试登录时,在行echo "Hello ".$_SESSION["name"]."<br/>";上得到未定义的索引名称echo "Hello ".$_SESSION["name"]."<br/>"; in index.php. 在index.php中。 My code is:- 我的代码是:-
index.php:- index.php:-

<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
?>
<!DOCTYPE html>
<html>
<head>
    <title>Login Registration</title>
    <link href="style.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>
    <script src="script.js"></script>
</head>
<body>
    <div id="wrapper">
    <!--Login div-->
        <div id="logincontainer"> 
            <form id="loginform" method="post">

                <h3>Login</h3>
                <div class="display-error" style="display: none;"></div>
                <input type="email" name="lemail" placeholder="Enter email address" required>

                <input type="password" name="lpassword" placeholder="Enter password" required>

                <input type="submit" value="Sign In">

                <p><a href="forgotpassword.php">Forgot Password</a></p>

                <p id="bottom">Don't have an account yet? <a href="#" id="signup">Sign up</a></p>

            </form>
        </div>

        <div id="signupcontainer">
            <form id="registerform" method="post">
                <h3>Register</h3>
                <div class="display-error" style="display: none;"></div>
                <input type="text" name="rname" placeholder="Full Name" required>

                <input type="email" name="remail" placeholder="Enter valid email" required>

                <input type="password" name="rpassword" placeholder="Password" required>

                <input type="text" name="rmobile" maxlength="10" pattern="[0-9]{10}" placeholder="Mobile" required>

                <input type="submit" value="Create Account">

                <p id="bottom">Already have an account? <a href="#" id="signin">Sign In</a></p>

            </form>


        </div>

        <!--Testing refresh portion-->
        <div id="after-login" style="display: none;">
            <?php
                echo "Hello ".$_SESSION["name"]."<br/>";
                echo '<a href="logout.php"><span class="glyphicon glyphicon-logout"></span>Sign Out</a><br/>';
            ?>
            <form id="events" method="post">
                Code Ardor<input type="checkbox" name="coding[]" value="ardor"> &nbsp;
                Designophy<input type="checkbox" name="coding[]" value="design"><br>
                <input type="submit" value="Submit" name="submit-btn">
            </form>
        </div>
        <!--Testing portion ends-->

    </div>

    <script>

        $(document).ready(function(){
            $("#loginform").submit(function(){
                var data = $("#loginform").serialize();
                checkRecords(data);
                return false;
            });
            function checkRecords(data){

                $.ajax({
                    url : 'loginprocess.php',
                    data : data,
                    type : 'POST',
                    dataType : 'json',
                    success: function(data){
                        if(data.code == 200){
                            //alert('You have successfully logged in');
                            //window.location='dashboard.php';
                            $("#logincontainer").hide();
                            $("#after-login").show();
                        }
                        else{
                            $(".display-error").html("<ul>"+data.msg+"</ul");
                            $(".display-error").css("display","block");
                        }
                    },
                    error: function(){
                        alert("Email/Password is Incorrect");
                }
                }); 
            }
        });

    </script>
    <!--Signup Ajax-->
    <script>

        $(document).ready(function(){
            $("#registerform").submit(function(){
                var data = $("#registerform").serialize();
                signupRecords(data);
                return false;
            });
            function signupRecords(data){

                $.ajax({
                    url : 'signupprocess.php',
                    data : data,
                    type : 'POST',
                    dataType : 'json',
                    success: function(data){
                        if(data.code == 200){
                            alert('You have successfully Signed Up \n Please Login now.');
                            setTimeout(function(){
                                location.reload();
                            },500);
                        }
                        else{
                            $(".display-error").html("<ul>"+data.msg+"</ul");
                            $(".display-error").css("display","block");
                        }
                    },
                    error: function(jqXHR,exception){
                        console.log(jqXHR);
                }
                }); 
            }
        });

    </script>

</body>

loginprocess.php loginprocess.php

    <?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
$errorMsg = "";
$email = trim($_POST["lemail"]);
$password = trim($_POST["lpassword"]);

if(empty($email)){
    $errorMsg .= "<li>Email is required</li>";
}
else{
    $email = filterEmail($email);
    if($email == FALSE){
        $errorMsg .= "<li>Invalid Email Format</li>";
    }
}

if(empty($password)){
    $errorMsg .= "<li>Password Required.</li>";
}
else{
    $password = $password;
}

if(empty($errorMsg)){
    $query = $db->prepare("SELECT password from users WHERE email = ?");
    $query->execute(array($email));
    $pwd = $query->fetchColumn();
    if(password_verify($password, $pwd)){
        $_SESSION['email'] = $email;
        //Testing piece
        $qry = $db->prepare("SELECT name from users WHERE email = ?");
        $qry->execute(array($email));
        $nme = $qry->fetchColumn();
        $_SESSION['name']=$nme;
        //Testing code ends
        echo json_encode(['code'=>200, 'email'=>$_SESSION['email']]);
        exit;
    }
    else{
        json_encode(['code'=>400, 'msg'=>'Invalid Email/Password']);
        exit;
    }
}
else{
    echo json_encode(['code'=>404, 'msg'=>$errorMsg]);
}

?>

As far as I can see the problem is that after login call you DO NOT reload the #after-login container contents - you only show it. 据我所知,问题是在登录呼叫后您不要重新加载#after-login容器的内容-您只显示它。

if(data.code == 200){
  //alert('You have successfully logged in');
  //window.location='dashboard.php';
  $("#logincontainer").hide();
  $("#after-login").show();
}

In the other words the #after-login contents only load on the first page load (before login) and then are not updated by your ajax call (only then you would have access to $_SESSION["name"] ). 换句话说, #after-login内容仅在首页加载时加载(登录之前),然后不通过ajax调用进行更新(只有这样,您才可以访问$_SESSION["name"] )。

IMHO proper solution would be to return the $_SESSION["name"] value in the loginprocess.php response and update it in the #after-login container before showing it (eg. use an empty span where the name should appear which you'll fill out on login). 恕我直言,正确的解决方案是在loginprocess.php响应中返回$_SESSION["name"]值,并在显示该值之前在#after-login容器中对其进行更新(例如,使用空跨度,其中名称应显示为请在登录时填写)。

//Something like
if(data.code == 200){
  //alert('You have successfully logged in');
  //window.location='dashboard.php';
  $("span#name_placeholder").text(data.name) //return name from loginprocess.php
  $("#logincontainer").hide();
  $("#after-login").show();
}

The best solution would to be to create a html element like this for the 最好的解决方案是为此类创建一个html元素。

<div id="after-login" style="display: none;">
           <h5 id="Username"></h5>
            <?php

                echo '<a href="logout.php"><span class="glyphicon glyphicon-logout"></span>Sign Out</a><br/>';
            ?>
            <form id="events" method="post">
                Code Ardor<input type="checkbox" name="coding[]" value="ardor"> &nbsp;
                Designophy<input type="checkbox" name="coding[]" value="design"><br>
                <input type="submit" value="Submit" name="submit-btn">
            </form>
        </div>

then after this include the username in the json like this 然后在此之后在用户名中包含用户名,就像这样

 $qry = $db->prepare("SELECT name from users WHERE email = ?");
            $qry->execute(array($email));
            $nme = $qry->fetchColumn();
            //$_SESSION['name']=$nme;
            //Testing code ends
            echo json_encode(['code'=>200, 'email'=>$_SESSION['email'],'username'=>$nme]);
            exit;

on the ajax call you can now access the json response with the username included and feed the span element with the username like this 在ajax调用上,您现在可以使用包含的用户名访问json响应,并使用以下用户名来输入span元素

    if(data.code == 200){
                                //alert('You have successfully logged in');
                                //window.location='dashboard.php';
                                $("#username").test(data.username);
                                $("#logincontainer").hide();
                                $("#after-login").show();
                            }

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

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