I am making a game for class and as with most games users are required to complete a level before moving on to the next. On my first level I use this under the If
statement that determines if the user has won the level:
if (passOnLevel == 0 && passengerCarrying == 0) {
alert("You Win!");
$.post("gameL2.php", {"Level1": "Level1"});
window.location.href='gameL2.php';
}
In my gameL2.php
file I have this at the top of the file:
<?php session_start(); ?>
<?php
if (isset($_POST['Level1'])) {
$_SESSION['Level1'] = $_POST['Level1'];
}
?>
The issue I am having is that when I use window.location.href='gameL2.php;
the $_POST is not set however if I removed window.location.href='gameL2.php;
it doesn't redirect the user to the next level but when I access the gameL2.php
file directly the $_POST is set. How can I make it redirect the users to level two but still set the post variable?
Problem is that $.post
is asynchronous command, so when you call it, you are calling location.href
right afterwards and $.post
did not have time to actually do the post.
So what you need to do is this:
if (passOnLevel == 0 && passengerCarrying == 0) {
alert("You Win!");
$.post("gameL2.php", {"Level1": "Level1"}, function() {
window.location.href='gameL2.php';
});
}
Basically you are passing a function that $.post
will call when it finishes. More at https://api.jquery.com/jQuery.post/
BUt, this will not resolve your problem with $_POST being unset in the second file, because calling $.post and opening gameL2.php are two calls, and data sending does not work that way.
So, in the end, you would probably be best off with:
if (passOnLevel == 0 && passengerCarrying == 0) {
alert("You Win!");
window.location.href='gameL2.php?Level1=Level1';
}
And then checking for $_GET["Level1"]
in your gameL2.php