0

I'm working on a project with a classmate, neither of us have previous experience with php and javascript. Our goal is to query a db and store the results in an array then pass that array to a javascript function. My partner wrote this bit of code which works but I was unable to successfully pass the array to our function in our javascript.

First, I tried using a local array which worked out fine when I tested it. Then I tried with the array generated in the above php segment, I've seen this question asked a few times but when I tried implementing some of the suggestions to encode the array as a JSON object that didn't work. Is there something wrong with the way we store the results from the database? I appreciate any help.

<?php
$query = "SELECT * FROM predictions ORDER BY course_no DESC";
$result = $db->query($query);
if ($result and $result->num_rows != 0) {
        @$result->data_seek(0);
        while($classesArray = @$result->fetch_assoc()) {
            extract($classesArray);
            echo $course_no . "<br>";
        }

      @$result->free(); // Release memory for resultset 
      @$db->close(); 
      echo " <script>var a = json_encode($classesArray);</script>";
}
?>


<script>
    $(document).ready(function(){       
        //var a = ["class1", "class2", "class3"];
        //loadClasses(a);'

        loadClasses(a);
    });      

function loadClasses(classesArray) {
    // #classesfield is the id of the classes dropdown
    for (var i = 0; i < classesArray.length; i++) {
        $("#classesdropdown").append('<input class="w3-check" type="checkbox">'); // add checkbox to our dropdown
        $label = $('<label class="w3-validate"></label>'); // crete element to inject
        $label[0].innerHTML= (classesArray[i]); // give it a class label
        $("#classesdropdown").append($label); // add it to our dropdown
        $("#classesdropdown").append('<br>'); // add new line to the dropdown
    }
}
</script>
11
  • Remove all of the @ chars in your code, they prevent error reporting and you will not be able to know if you have some errors in your code or not. What exactly is the problem? Commented Dec 4, 2016 at 1:45
  • You should have your PHP page get called using AJAX. Commented Dec 4, 2016 at 1:47
  • try to echo the entire <script> element Commented Dec 4, 2016 at 1:48
  • @Dekel I'm just not populating a dropdown with the data from the array when I try using the array generated in the php. Commented Dec 4, 2016 at 1:49
  • what is loadClasses function? what is the actual output (the final html) you have? Commented Dec 4, 2016 at 1:50

1 Answer 1

2

The proper way to do this is to have a simple HTML page which requests the JSON via an AJAX call to a PHP page which in-turn fetches the Database data, processes it, and returns JSON data.

SQL Data

I made up the following data as an example, but the PHP does not care about the fields. You will just return all the data in the table as a JSON object array.

CREATE TABLE IF NOT EXISTS `course` (
  `course_no` int(11) NOT NULL,
  `course_name` varchar(64) NOT NULL,
  `course_desc` varchar(255) DEFAULT NULL,
  `course_credits` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `course` ADD PRIMARY KEY (`course_no`);

INSERT INTO `course` (`course_no`, `course_name`, `course_desc`, `course_credits`) VALUES
(1, 'Algebra', 'Learn how to perform basic arithmetic.', 4),
(2, 'Biology', 'Learn how to classify organisms.', 4),
(3, 'Literature', 'Read a lot of books.', 4),
(4, 'Physical Education', 'Get active!', 2);

retrieveClasses.php

Connect, query, and return the class information from the database as a JSON array.

<?php
$mysqli = new mysqli('localhost', 'admin', '', 'test');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM `course`")) {
    while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $myArray[] = $row;
    }
    echo json_encode($myArray);
}
$result->close();
$mysqli->close();
?>

index.html

Populate the dropdown with the JSON data returned from the AJAX call.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Ajax Populate Using PHP DB</title>
        <meta name="description" content="PHP Database Ajax Populate">
        <meta name="author" content="Self">
        <link rel="stylesheet" href="css/styles.css?v=1.0">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $.getJSON('./retrieveClasses.php', function(records) {
                    loadClasses(records.map(function(record) {
                        return record['course_no'] + '] ' + record['course_name'];
                    }));
                });
            });

        function loadClasses(classesArray) {
            // #classesfield is the id of the classes dropdown
            for (var i = 0; i < classesArray.length; i++) {
                $('#classesdropdown').append('<input class="w3-check" type="checkbox">'); // add checkbox to our dropdown
                $label = $('<label class="w3-validate"></label>'); // crete element to inject
                $label.text(classesArray[i]); // give it a class label
                $('#classesdropdown').append($label); // add it to our dropdown
                $('#classesdropdown').append('<br>'); // add new line to the dropdown
            }
        }
        </script>
    </head>
    <body>
        <div id="classesdropdown"></div>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.