简体   繁体   English

使用AJAX发布和重定向后如何访问PHP变量?

[英]How to access PHP variables after posting and redirecting with AJAX?

I'm making a login page in PHP where the user inputs a username. 我正在用PHP创建一个登录页面,用户在其中输入用户名。 If the username is valid, the user is redirected to another page, where the username they used is printed. 如果用户名有效,则将用户重定向到另一个页面,在该页面上打印他们使用的用户名。 If the username is not valid, the page prompts them to enter a valid username and the page reloads. 如果用户名无效,则页面会提示他们输入有效的用户名,然后页面会重新加载。

My problem is in 'POSTing' the valid "username" variable from the login page to the page the user is redirected to. 我的问题是将有效的“用户名”变量从登录页面“发布”到用户重定向到的页面。

I know that in my form tags from my login page, I can put: 我知道在登录页面的表单标签中,我可以输入:

<form action='pageToPostTo.php' method='POST'>

</form>

However, my problem with this is that, as soon as the user hits submit, this ALWAYS seems to redirect to pageToPostTo.php. 但是,我的问题是,一旦用户点击“提交”,此“总是”似乎就会重定向到pageToPostTo.php。 As a result, if the username is invalid, I don't know how to avoid this redirection. 结果,如果用户名无效,我不知道如何避免这种重定向。

Instead, I used jQuery's ".ready" and ".click" to execute javascript code that verifies whether the username is valid when the user clicks "submit." 取而代之的是,我使用jQuery的“ .ready”和“ .click”来执行JavaScript代码,以验证用户单击“提交”时用户名是否有效。 If it's valid, then Ajax's "POST" method is called. 如果有效,那么将调用Ajax的“ POST”方法。 If it's not valid, then the login page prompts and reloads. 如果无效,则登录页面会提示并重新加载。

function isValid(username) {
    return true;
}

$(document).ready(function () {

    $('input#submit').click(function (event) {

        event.preventDefault();

        if(isValid(username.value)) {
            postUser();
        }

        else {
            alert("Invalid Username");
            location.reload();
        }
    });
});

postUser() is shown below: postUser()如下所示:

function postUser() {

    var username = username.value;

    $.ajax({
        url: 'pageToPostTo.php',
        type: 'POST',
        data: {getUsername: username}, // username = "danny"
        success: function(response) {
            alert(response);    // Outputs: "Your username is: danny"
            window.location.href = 'pageToPostTo.php'; // Outputs: "Your username is: Notice: Undefined index: getUsername..."
        }
    });
}

"alert(response)" within the "success" function of my Ajax post object properly evaluates $_POST['getUsername']. 我的Ajax发布对象的“成功”函数中的“警告(响应)”正确评估$ _POST ['getUsername']。 This shows me that my Ajax post is working perfectly. 这表明我的Ajax帖子运行良好。

THIS IS WHERE MY PROBLEM IS: As soon as I redirect to pageToPostTo.php, $_POST['getUsername'] stops evaluating and instead returns "Notice: Undefined index: getUsername". 这是我的问题所在:当我重定向到pageToPostTo.php时,$ _ POST ['getUsername']停止评估,而是返回“ Notice:Undefined index:getUsername”。

Ajax's "post" method seems to work but the redirection is missing what Ajax "posted." Ajax的“发布”方法似乎有效,但是重定向缺少Ajax“发布”的内容。

Is there a way to redirect to "pageToPostTo.php" after the Ajax "post" method executes, such that after the redirection, I can retrieve what has been posted by Ajax with $_POST['getUsername']? 在执行Ajax“ post”方法之后,是否可以重定向到“ pageToPostTo.php”,这样在重定向之后,我可以使用$ _POST ['getUsername']检索Ajax发布的内容?

If not, why not and what alternatives do I have to get the same functionality? 如果不是,为什么不呢?我必须有哪些替代方案才能获得相同的功能?

Previously I was using localStorage.setItem("usernameStorage", username.value) and localStorage.getItem(...) to transfer variables between by php files. 以前,我使用localStorage.setItem(“ usernameStorage”,username.value)和localStorage.getItem(...)在php文件之间传输变量。 Are there any disadvantages to doing it this way? 这样做有什么弊端吗?

Snip from my loginPage.php: 从我的loginPage.php中截取:

<form name="login">
    <p>Username: <input type="text" id="username" ></p>
    <input type="submit" id="submit">
</form>

pageToPostTo.php: pageToPostTo.php:

<?php
    $validUser = $_POST['getUsername'];
    echo "Your username is: " . $validUser;
?>

PS The function to verify whether a username is valid must be in JavaScript. PS验证用户名是否有效的函数必须在JavaScript中。

You just have to start using developed solutions in this case. 在这种情况下,您只需要开始使用开发的解决方案即可。 Like a work around i propose you to use $_SESSION to store your data while you transfer it between the files. 像变通一样,我建议您在文件之间传输数据时使用$_SESSION来存储数据。 In your case: After User login, program validate and if it is success, save it in 您的情况:用户登录后,程序验证,如果成功,则将其保存在

$_SESSION['user_id'] = $user_id

after that you make a redirection to your file: pageToPostTo.php: and first of all check if user_id exist in session, if not -> redirect to login page , if exist, assign value to $var and do what you need to do with that. 之后,您将重定向到文件: pageToPostTo.php: ,首先检查会话中是否存在user_id,如果不存在,则重定向到登录页面,如果存在,则将值分配给$ var并执行所需的操作那。

You have to execute your login php at the same page, and make the redirection ONLY in case if validation was successful. 您必须在同一页面上执行登录php,并且仅在验证成功的情况下进行重定向。 that's is addition to my answer. 那是我的回答的补充。

You can use form submit instead of button click in jQuery. 您可以在jQuery中使用表单提交而不是单击按钮。
Example : 范例:
Here is your html form: 这是您的html表单:

<form action='pageToPostTo.php' id="action-form" method='POST'></form>

Modified JQuery Script : 修改后的JQuery脚本:

$("#action-form").submit(function(){
  if(!isValid(username.value)) {
    alert("Invalid Username");
    return false;
  }
});

In that way, If user name is valid then it will automatically redirect on 'pageToPostTo.php'. 这样,如果用户名有效,则它将自动在“ pageToPostTo.php”上重定向。 There is no need to hit ajax request. 无需点击ajax请求。

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

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