Skip to content
Advertisement

Javascript: Refresh current page after event change $_SESSION in a other page

I need help for a subtlety. I created a multilingual site without changing using the same php file, I just modify its content. For this I use sessions. So I configured 2 buttons: FR and EN which change the language. I go through another php file. With this code it works if I manually reload the page. But if I use:

location.reload(true);

it doesn’t work and i want to automatically reload the page without user intervention. Does anyone have the solution? Thanking you, Regards,

my code index.php :

<?php
session_start();
if(isset($_SESSION['lang']) == false){
    $_SESSION['lang'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <link href="_style/style-master.css" rel="stylesheet" type="text/css">
        <script type='text/javascript'>
    function setSession(lang) {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "change.php?lang=" + lang, true);
        xmlhttp.send();
        //here reload and refresh page after execute code in change.php
    }
</script>
        <title></title>
    </head>
    <?php
    if($_SESSION['lang'] == "fr"){
        echo "<body>";
        echo "<p>Page française</p>";
        echo "<a href="javascript:setSession('en')"><input type='submit' value='EN'></a>";
        echo "<a href="javascript:setSession('fr')"><input type='submit' value='FR'></a>";
        echo "</body>";
    } else{
        echo "<body>";
        echo "<p>English page</p>";
        echo "<a href="javascript:setSession('en')"><input type='submit' value='EN'></a>";
        echo "<a href="javascript:setSession('fr')"><input type='submit' value='FR'></a>";
        echo "</body>";
    }
    ?>
</html>

change.php :

<?php
    session_start();
    if(isset($_REQUEST['lang']))
    {
    $lang = $_REQUEST['lang'];
    $_SESSION['lang'] = $lang;
    }
?>

Advertisement

Answer

Your code reloads the index.php immediately and doesn’t even wait for the request (to change.php) to be sent.

You can handle the onreadystatechange event of XMLHttpRequest, specifically you’re looking for state 2, which is HEADERS_RECEIVED, or any later state.

When the PHP script sends headers, it means it already finished executing (and set the session). And you can safely reload the index page.

function setSession(lang) {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 2) {
            //here reload and refresh page after execute code in change.php
            location.reload(true);
        }
    }
    xmlhttp.open("GET", "change.php?lang=" + lang, true);
    xmlhttp.send();
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement