0

I am currently creating a school project I am trying to query data from a database and return it and display it using AJAX. The way the webpage works is by the user selects a date and information they have previously submitted into the website is pulled from the database and displayed in a table. As of right now, when the user clicks on a date, nothing is displayed in the table. I have checked the network tab in dev tools and it is showing an empty array for some reason.

I have ensured that there is definitely data in the table that it is querying. I have tried chaning the queries from using SELECT * FROM to selecting the columns individually. I think it is something to do with the json_encode section or perhaps a part of the AJAX code that isn't working properly.

diary.php

<?php
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);

    session_start();

    include "src/config.php";

    //checks to see if the user is logged in
    if(!isset($_SESSION['email'])){
        header("location: login.php");
    }

    
?>
<!DOCTYPE html>
<html>
    <head>
        <title>myepilepsy | Diary</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>


        <link rel="stylesheet" type="text/css" href="css/diary.css">
        <link rel="stylesheet" type="text/css" href="css/styles.css">

        <meta charset="UTF=8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    </head>
    <body>
        <!-- Calendar -->
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Calendar</h3>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <div id="datepicker"></div>
                                </div>
                                <div class="col-md-8">
                                    <h3 id="selected-date"></h3>
                                    <table class="table" id="diary-table">
                                        <thead>
                                            <tr>
                                                <th>Appointments</th>
                                                <th>Auras</th>
                                                <th>Medications</th>
                                                <th>Mood</th>
                                                <th>Seizures</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td id="Appointments"></td>
                                                <td id="Auras"></td>
                                                <td id="Medications"></td>
                                                <td id="Mood"></td>
                                                <td id="Seizures"></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script>
            $(document).ready(function() {
                $('#datepicker').datepicker({
                    format: 'yyyy-mm-dd',
                    autoclose: true,
                    todayHighlight: true,
                    endDate: new Date()
                });

                $('#datepicker').on('changeDate', function(e) {
                   var selectedDate = $('#datepicker').datepicker('getDate').toISOString().slice(0, 10);

                   $('#selected-date').text('Selected Date: ' + selectedDate);

                    //send a post request to getData.php using AJAX
                    $.ajax({
                        type: "POST",
                        url: "src/getData.php",
                        data: {
                            user_id: <?php echo $_SESSION['user_id']; ?>,
                            selected_date: selectedDate
                        },
                        success: function(response) {
                            console.log(response);
                            //parse the json-encoded response
                            var data = (response);

                            //update table with returned data
                            $('#Appointments').html(data.appointments);
                            $('#Auras').html(data.auras);
                            $('#Medications').html(data.medications);
                            $('#Mood').html(data.mood);
                            $('#Seizures').html(data.seizures);

                            //create and update table with returned data
                            var diaryTable = $('#diary-table');
                            diaryTable.find('tbody').empty(); //clear existing rows only

                            var appointmentsData = data.appointmentsData || [];
                            var aurasData = data.aurasData || [];
                            var medicationsData = data.medicationsData || [];
                            var moodData = data.moodData || [];
                            var seizuresData = data.seizuresData || [];

                            //log the appointmentsData array to the console
                            //console.log(appointmentsData);

                            //loop through the data and add rows to table
                            for (var i = 0; i < appointmentsData.length; i++) {
                                var row = $('<tr>');
                                var appointment = $('<td>').text(appointmentsData[i]);
                                var aura = $('<td>').text(aurasData[i]);
                                var medication = $('<td>').text(medicationsData[i]);
                                var mood = $('<td>').text(moodData[i]);
                                var seizure = $('<td>').text(seizuresData[i]);

                                row.append(appointment);
                                row.append(aura);
                                row.append(medication);
                                row.append(mood);
                                row.append(seizure);
                                diaryTable.append(row);
                            }
                        },
                        error: function() {
                            alert('Error fetching data');
                        }
                    });
                });
            });
        </script>
    </body>
</html>

getData.php

<?php
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);

    session_start();

    //include db conn
    include "config.php";

    $selected_date = $_POST['selected_date'];

    //func to get appointments data
    function getAppointments($user_id, $selected_date) {
        global $conn;
        $stmt = $conn->prepare("SELECT * FROM appointments WHERE user_id = ? AND appointment_date = ?");
        $stmt->bind_param("is", $_SESSION['user_id'], $selected_date);
        $stmt->execute();
        if ($stmt->error) {
            die("Query failed: " . $stmt->error);
        }
        $result = $stmt->get_result();
        return $result;
    }

    // func to get aura data
    function getAuras($user_id, $selected_date) {
        global $conn;
        $stmt = $conn->prepare("SELECT * FROM auras WHERE user_id = ? AND aura_date = ?");
        $stmt->bind_param("is", $_SESSION['user_id'], $selected_date);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }

    // func to get med data
    function getMedications($user_id, $selected_date) {
        global $conn;
        $stmt = $conn->prepare("SELECT * FROM medications WHERE user_id = ? AND date_taken = ?");
        $stmt->bind_param("is", $_SESSION['user_id'], $selected_date);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }

    //func to get mood
    function getMood($user_id, $selected_date) {
        global $conn;
        $stmt = $conn->prepare("SELECT * FROM mood WHERE user_id = ? AND mood_date = ?");
        $stmt->bind_param("is", $_SESSION['user_id'], $selected_date);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }

    //func to get seizures
    function getSeizures($user_id, $selected_date) {
        global $conn;
        $stmt = $conn->prepare("SELECT * FROM seizures WHERE user_id = ? AND seizure_date = ?");
        $stmt->bind_param("is", $_SESSION['user_id'], $selected_date);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }

    $appointments = getAppointments($_SESSION['user_id'], $selected_date);
    $auras = getAuras($_SESSION['user_id'], $selected_date);
    $medications = getMedications($_SESSION['user_id'], $selected_date);
    $mood = getMood($_SESSION['user_id'], $selected_date);
    $seizures = getSeizures($_SESSION['user_id'], $selected_date);

    $data = array(
        'appointments' => $appointments,
        'auras' => $auras,
        'medications' => $medications,
        'mood' => $mood,
        'seizures' => $seizures
    );

    header('Content-Type: application/json');
    echo json_encode($data);

?>
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Do you have to use mysqli? It's the least beginner-friendly SDK. PDO is much easier to use – Phil Mar 16 '23 at 22:34
  • Your issue is that you are not **fetching** any data. `get_result()` just returns a [mysqli_result](https://www.php.net/manual/lass.mysqli-result.php) object. I suggest if you want to continue using mysqli, refer to this tutorial ~ https://phpdelusions.net/mysqli_examples/prepared_select. If on the other hand you want to make life easier, refer to this tutorial ~ https://phpdelusions.net/pdo – Phil Mar 16 '23 at 22:36
  • Replace `$stmt->get_result()` with `stmt->fetch(PDO::FETCH_ASSOC)` – Salah a Mar 17 '23 at 02:49

0 Answers0