Create chart.js using ajax by calling another php file using XMLHttpRequest

I’m trying to create a Dash board web page. I’m connected to MS SQL 2008 and using PHP 7.3

the page uses AJAX create chart.js using XMLHttpRequest() to get sql query results from another page

dashboard.php is the main page that does the request prcweeksaleschart.php is the page that is called by ajax

prcweeksaleschart.php handles the POST request and generates the SQL data successfully then creates the element and the related chart

the element and related chart code are then entered in the dashboard page

the problem is that the dashboard page doesn’t load the chart at all

below is the code for dashboard.php

<?php

// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: index.php");
    exit;
}

if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true) {
  if ($_SESSION["badmin"] != 1) {
    header("location: index.php");
  }
}

// Include config file
require_once "config.php";

$defdate = date("Y-m-d");

 ?>


 <!DOCTYPE html>
 <html lang="en">
 <head>
   <title>BMAM|Rpt - DashBoard</title>
   <?php Include "bs4.php" ?>

   <!--AJAX Week Sales-->
   <script>
   function genweeksalesrep() {
     // Creating the XMLHttpRequest object
     document.getElementById('divweeksales').innerHTML = '<div class="progress"><div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="100" aria-valuemin="100" aria-valuemax="100" style="width: 100%"></div></div>';
     document.getElementById('divweeksaleschart').innerHTML = '<div class="progress"><div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="100" aria-valuemin="100" aria-valuemax="100" style="width: 100%"></div></div>';
     //Details
     var request = new XMLHttpRequest();
     // Instantiating the request object
     request.open("POST", "prc/prcweeksales.php");
     // Defining event listener for readystatechange event
     request.onreadystatechange = function() {
        // Check if the request is compete and was successful
        if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
            // Inserting the response from server into an HTML element
            document.getElementById("divweeksales").innerHTML = request.responseText;
          }
        };
        // Retrieving the form data
        var myForm = document.getElementById("frmweeksales");
        var formData = new FormData(myForm);
        // Sending the request to the server
        request.send(formData);
        //Chart
        var requestc = new XMLHttpRequest();
        // Instantiating the request object
        requestc.open("POST", "prc/prcweeksaleschart.php");
        // Defining event listener for readystatechange event
        requestc.onreadystatechange = function() {
           // Check if the request is compete and was successful
           if(requestc.readyState === XMLHttpRequest.DONE && requestc.status === 200) {
               // Inserting the response from server into an HTML element
               document.getElementById("divweeksaleschart").innerHTML = requestc.responseText;
               //$('#myChart').remove();
               //$('#divweeksaleschart').append('<canvas id="myChart" width="100%" height="50px"></canvas>');
               myChart.reset();
               myChart.update();
             }
           };
           // Retrieving the form data
           var myFormc = document.getElementById("frmweeksales");
           var formDatac = new FormData(myFormc);
           // Sending the request to the server
           requestc.send(formDatac);



      }

    </script>
    <!--AJAX Week Sales-->

<!--Java Function to clear inner html-->
   <script type="text/javascript">
    $(document).ready(function(){
      $("#frmweeksalesresetbtn").click(function(){
        $("#divweeksales").html("Clear!");
        $("#divweeksaleschart").html("");
      });
    });
   </script>

 </head>
 <body>
   <?php
   include "header.php";
   ?>


   <div class="container-fluid" style="font-size: 90%;">

     <h5>DASH BOARD</h5>
     <hr>
     <div class="row">
       <div class="col">

         <div class="card">
           <div class="card-header">
             <h5>Weekly Sales</h5>
             <div class="row">
               <div class="col">
                 <form class="form-inline" id="frmweeksales">
                   <select class="form-control form-control-sm mb-2 mr-sm-2" name="company">
                     <option value="1">Bawabet Al Maamoura</option>
                     <option value="2" selected>Nitrogen</option>
                   </select>
                   <!--<label class="mr-sm-2" for="datet">Date:</label>-->
                   <input class="form-control form-control-sm mb-2 mr-sm-2" type="date" name="todate" id="datet" value="<?php echo $defdate; ?>">
                   <input type="button" class="btn btn-primary btn-sm mb-2" value="Refresh" id="frmweeksalesbtn" onclick="genweeksalesrep()">
                 </form>
               </div>
               <div class="col">
                 <button class="btn btn-secondary btn-sm float-right" id="frmweeksalesresetbtn">Reset</button>
               </div>
             </div>
           </div>
           <div class="card-body">
             <div class="row">
               <div class="col-6" id="divweeksales">

               </div>
               <div class="col-6" id="divweeksaleschart">

               </div>
             </div>
           </div>
         </div>
       </div>
     </div>


   </div>


   <div class="container-fluid">
     <footer class="footer">
       <?php Include "footer.php" ?>
     </footer>
   </div>
 </body>
 </html>

and here is the code in prcweeksaleschat.php:

<?php

// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: index.php");
    exit;
}

if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true) {
  if ($_SESSION["badmin"] != 1) {
    header("location: index.php");
  }
}

// Include config file
require_once "../config.php";

$brands = $thisweek = $lastweek = $color1 = $color2 = "";
$arr = array();
 ?>

 <?php
 if ($_SERVER["REQUEST_METHOD"] == "POST") {
     $todate = htmlspecialchars(trim($_POST["todate"]));
     $company = htmlspecialchars(trim($_POST["company"]));

     $server = DB_SERVER;
     $options = array(  "UID" => DB_USERNAME,  "PWD" => DB_PASSWORD,  "Database" => DB_NAME, "CharacterSet" => "UTF-8", "ReturnDatesAsStrings" => true);
     $conn = sqlsrv_connect($server, $options);
     echo $conn."<br>";
     $sqlsalesrep = "EXEC prcweeksales '".$todate."', " . $company . ",1";
     echo $sqlsalesrep."<br>";
     $querysalesrep = sqlsrv_query($conn, $sqlsalesrep);
     echo $querysalesrep."<br>";
     if ($querysalesrep === false){
       exit("<pre>".print_r(sqlsrv_errors(), true));
     }
     if ($querysalesrep != false) {
       while ($rowasalerep = sqlsrv_fetch_array($querysalesrep)){
         $arr[] = $rowasalerep;
       }
       for ($i=0; $i < count($arr) ; $i++) {
         $brands .= "'".$arr[$i][1]."',";
         $thisweek .= $arr[$i][2].",";
         $lastweek .= $arr[$i][3].",";
         $color1 .="'#c45850',";
         $color2 .="'#3e95cd',";
       }
       $brands = rtrim($brands, ",");
       $thisweek = rtrim($thisweek, ",");
       $lastweek = rtrim($lastweek, ",");
       $color1 = rtrim($color1, ",");
       $color2 = rtrim($color2, ",");
       //echo $brands;
       //echo "<br>";
       //echo $thisweek;
       //echo "<br>";
       //echo $lastweek;
     }

   }
  ?>


  <canvas id="myChart" width="100%" height="50px"></canvas>
  <script>
  var ctx = document.getElementById('myChart');
  var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
      labels: [<?php echo $brands; ?>],
      datasets: [{
        label: 'This week',
        backgroundColor: [<?php echo $color1; ?>],
        data: [<?php echo $thisweek ?>]
      },
      {
        label: 'Last week',
        backgroundColor: [<?php echo $color2; ?>],
        data: [<?php echo $lastweek ?>]
      }],

    },
    options: {
      legend: { display: true },
      title: {
        display: true,
        text: 'Weekly Sales Chart'
      }
    }
     });
   </script>

My php is very low level, but do you have an opening <php ? tag in the dashboard file? I don’t see one.

yes I do, but I missed it when I copied the code from my project