-3

I'm new to PHP, I want to have a button on my index page, when the button is clicked, it will trigger page 2 to display a DIV with my own content but I will remain in index page without redirect to page 2, and DIV on page 2 is hidden when the button is not clicked.

Is there any way I can achieve this?

Bender Bending
  • 624
  • 7
  • 23
Kenneth
  • 21
  • 2

1 Answers1

0

If you really stand behind your bad idea, just go for:

if(isset($_POST['submit'])) {
echo "<div>My hidden content</div>"
}

This will be on secondary page ^

<form action="page2.php" method="post">
<button name="submit">Submit</button>
</form>

This will be on your index page ^

As guys mentioned before, it's better practice to use JavaScript to do that. Call a post request without refreshing the page. Or if you want open connection between client and server, use node.js (server-side JavaScript)

Well, if you want to stay on the first page after click on the button and you won't use any JavaScript, you can do it also this way. But it will get redirected 2 times, so it's kinda... Not efficient and client friendly.

Your second page:

if(isset($_POST['submit'])) {
setcookie("CLICKED",'ThisValueDoesntMatter',time()+31556926 ,'/');
header("HTTP/1.1 301 Moved Permanently");
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
if(isset($_COOKIE['CLICKED'])) {
echo "<div>My hidden content</div>"
}

It is also insecure if the button is supposed to be on some page with authentication. The index page stays the same. NOTE: The cookie has lifetime of 1 year.

Martin Joneš
  • 105
  • 1
  • 13
  • Hi martin, i have tried your solution is working but i like to remain at my index page after click on the button, is there any way to archive that ? – Kenneth Aug 04 '17 at 08:44
  • It is possible by making a POST request via JavaScript. This could help you out [link](https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest) However, when you remain on your first page and than after get onto the second one, the div wouldn't appear. You have 2 chooses. By clicking on button, you can create session or you can create client side cookie. If there is cookie in browser, it will send data to server, server finds out you have clicked on button earlier and will show the div. – Martin Joneš Aug 04 '17 at 09:25