PHP/Javascript passing message to another page

眉间皱痕 提交于 2019-12-01 13:14:24

If I understand you correctly, your problem is that the action, and the displaying of the confirmation take place on different pages.

One approach to do this is to store the message that is to be displayed on the next page in the user's session:

// insert.php
$_SESSION["user_message"] = "You were awarded +2 points.";

and output it on the following page:

// thankyou.php
echo $_SESSION["user_message"]; // Or show the box, or whatever
$_SESSION["user_message"] = null; // Clean up

the potential downside to this is that if the user has two or more pages/tabs of your site open, and navigates a lot across them, the message may appear in the wrong context. For example, if I click "save" in tab A, and refresh tab B, it could happen that the message intended for tab A is displayed in tab B.

You could help that by adding a randomly generated key to the message's variable name, and passing that key on to the page you want to display the message on:

// insert.php
$key = "123456"; // Insert random generation method here, e.g. using rand()
$_SESSION["user_message_$key"] = "You were awarded +2 points.";
header ("Location: thankyou.php?message=$key"); // Pass the key to the next page

// thankyou.php
$key = $_GET["message"]; // No sanitation necessary here AFAICS
echo $_SESSION["user_message_$key"]; // Or show the box, or whatever
$_SESSION["user_message_$key"] = null; // Clean up

This is very elegant because

  • the message you want to display remains in your internal session store, and at no point is passed on in the browser, reducing the risk of security holes and such.

  • by unsetting the session variable, you make sure the message is shown only once, even if the user reloads the page.

If insert.php is being opened by the page that needs to display the mesage, you can use window.opener to access the originating page. I think something like this might work:

window.opener.$("#message").html($("#box").html()).fadeIn("slow");

I'm not sure if I understand correctly, but if the user makes the input in a field on index.php, then maybe you could send it to insert.php with an ajax request, and use the callback of the ajax to display the notice to the user?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!