0

I'm trying to have session variables updated with an XMLHttpRequest, and have them output on the page.

When loading the page, they don't show. It just says "today: ", "yesterday: ", without the session variables.

When I reload the page, they show correctly. I don't understand why it's not working the first time -- clearly something to do with the order of the code, but from my understanding, everything here is as it should be?

JavaScript:

    //simple strings to demonstrate problem:
    var date = "04052020";
    var yesterday = "03052020";

    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (this.readyState==4 && this.status==200) {

            document.getElementById("streak").innerHTML = "<?php
                echo "<br> today: ".$_SESSION['todayDate'];
                echo "<br> yesterday: ".$_SESSION['yesterdayDate'];
            ?>";
        }
    }
    xmlhttp.open("GET","../practice/includes/stats.inc.php?date="+date+yesterday+"h",true);
    xmlhttp.send();

PHP file (stats.inc.php):

    $datesIn = $_GET['date'];

    $today = substr($datesIn, 0, 8);
    $_SESSION['todayDate'] = $today;

    $yesterday = substr($datesIn, 8, 8);
    $_SESSION['yesterdayDate'] = $yesterday;
Joseph
  • 101
  • 9
  • 2
    The PHP program containing the ` – Quentin Jun 04 '20 at 10:46
  • Thanks @Quentin. I've solved my problem, the way I did it was to echo the session variables within the PHP file, separated with ";", then split the responseText in the JavaScript and use that instead of the session variables directly – Joseph Jun 04 '20 at 11:15

0 Answers0