Utilize JavaScript to extract and exhibit various SQL records stored within a multidimensional array

How can I use JS, JQuery, PHP, and MySQLi to automatically generate an HTML table within a div on a webpage? The table should display data based on user-input search criteria. For example, the user enters a start date and end date, clicks a button, which then sends a request to a PHP file to query a MySQLi table. The PHP file returns a multi-dimensional array to JS that processes the data to build the HTML table.

From the user's perspective, they input a range of dates and see a list of bookings made between those dates displayed elsewhere on the same page.

To manage my code effectively, I want to keep my JS script in a separate file referenced in the HTML header and the PHP script in another file referenced from the JS script.

This is a snippet of what my JS script looks like:

$(document).ready(function(){
    var startDate = new Date (2017,11,25);
    var stopDate = new Date (2017,11,31);
    displayBookings = function(startDate, stopDate) {
        $.post("php/getBookings.php", {
        startDate: startDate, 
        stopDate: stopDate
        },
        function(data){
            html = "<table>";   
            var i, j, result = JSON.parse(data); 
            while (i=0, i <= result.length, i++) {
               while (j=0, j <= result[i].length, j++) {          
                    html+= "<tr><td>"+result[i][j]+"</td></tr>";
                }
            }
            html += "</table>";
            $('#bookings').html(html);
        });
    };
});

This is a snippet of my PHP script ('getBookings.php'):

<?php
$startDate = date('Y-m-d',strtotime($_POST["startDate"]));
$stopDate = date('Y-m-d',strtotime($_POST["stopDate"]));
$con = mysqli_connect("localhost","userid","password","database");
$sql = "SELECT * FROM bookings WHERE date BETWEEN '$startDate' AND '$stopDate'";
$result = mysqli_query($con,$sql);
$rows = mysqli_num_rows($result);
for ($i = 0; $i < $rows; $i++) {
    $row = mysqli_fetch_array($result);
    $newArray[$i]['reference'] = $row['reference'];
    $newArray[$i]['name'] = $row['name'];
    $newArray[$i]['price'] = $row['price'];
}
mysqli_free_result($result);
mysqli_close($con);
echo json_encode($newArray);
?>

My HTML code includes:

<button onClick='displayBookings()'>Press</button>
<div id="bookings"></div>

When I press the button, I receive the error message:

Uncaught TypeError: Cannot read property 'length' of null

As a beginner, I'm sure I've made a basic mistake. Can someone provide assistance?

Answer №1

It seems like the issue lies in this part:

while (i=0, i <= result.length
should actually be: while (i=0, i < result.length, and the same applies for j.

You might want to consider using map or reduce:

$(document).ready(function () {
  var startDate = new Date(2017, 11, 25);
  var stopDate = new Date(2017, 11, 31);
  displayBookings = function (startDate, stopDate) {
    $.post("php/getBookings.php", {
      startDate: startDate,
      stopDate: stopDate
    },
      function (data) {
        console.log(JSON.stringify(data,undefined,2));
        html = "<table>" +
          data.map(
            row=>{
              row.map(
                item=>`<tr><td>${item}</td></tr>`
              ).join("");
            }
          ).join("") + "</table>";
        $('#bookings').html(html);
      });
  };
});

If your PHP returns an object with properties as JSON, you can try the following approach:

$(document).ready(function () {
  var startDate = new Date(2017, 11, 25);
  var stopDate = new Date(2017, 11, 31);
  displayBookings = function (startDate, stopDate) {
    $.post("php/getBookings.php", {
      startDate: startDate,
      stopDate: stopDate
    },
      function (data) {
        console.log(JSON.stringify(data,undefined,2));
        html = "<table>" +
          Object.keys(data).map(
            key=>{
              Object.keys(data[key]).map(
                rowKey=>`<tr><td>${data[key][rowKey]}</td></tr>`
              ).join("");
            }
          ).join("") + "</table>";
        $('#bookings').html(html);
      });
  };
});

The challenge with objects is that they do not guarantee the order, for instance:

Object.keys({
  first: 1,
  second:2
});

Will typically return ["first","second"] but not always.

In this case, it would be best to go with the initial code block but modify your PHP like so:

$newArray = array()
for ($i = 0; $i < $rows; $i++) {
  $row = mysqli_fetch_array($result);
  $newArray[$i] = array(
    $row['reference'],
    $row['name'],
    $row['price']
  );
}

If the error message data.map is not a function was due to PHP's handling of arrays, with this PHP adjustment you can utilize the JavaScript from the first block (data.map and row.map)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The specified type does not meet the constraint as it lacks the required index signature

I'm currently working on refactoring a TypeScript project that utilizes React Hooks. While I have some knowledge of TypeScript, I am still more of a beginner than an expert. My main goal is to create reusable code for this project through the use of ...

Why isn't the transparency feature in graphicsmagick working?

Currently, I am utilizing the graphicsmagick npm package which can be found at https://www.npmjs.com/package/gm. In my attempt to write a piece of code similar to the one below, I am struggling to make it function properly with stream. The image file myimg ...

Numerous instances of Codemirror

I have the ability to generate and exhibit multiple dynamic codemirror instances, however, I am having trouble referencing them using the code snippet below. I suspect that the problem lies in creating a dynamic function name (not entirely sure how to ac ...

The Bootstrap nav-link class functions perfectly in Firefox, smoothly guiding users to the appropriate section. However, it seems to be experiencing some issues

I am currently working on customizing a one-page web template and I don't have much experience with Bootstrap. The template can be found at . My issue is that the menu items are not functional in Chrome. When I click on any menu item, nothing happens ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

What is the process for transforming a self-iterating ArrayList into JSON with the help of Jackson

I need to transform a List of data into the JSON structure shown below. I have retrieved the data from MySQL into an ArrayList and defined the EducationDTO POJO class. { "id": "1", "name": "EDUCATION", "data": "", "children": [ { "id": "1.1", ...

What is React.js's approach to managing CSS files?

Currently, I am enrolled in Bootcamp at Scrimba where they utilize an online platform for teaching various courses. One of the topics covered is React and involves working with CSS files. When working on my local machine, I typically use the index.css file ...

Currently focused on developing vertical sliders that can be manipulated by dragging them up or down independently

https://i.stack.imgur.com/NgOKs.jpg# I am currently working on vertical sliders that require dragging up and down individually. However, when I pull on the first slider, all sliders move together. The resetAllSliders button should also work independently, ...

The second JSP page fails to load following an AJAX POST request

The following code snippet is found in page1.jsp. $.ajax({ type: "post", url: "page2.jsp", data: newdata, success:function(msg){ return msg; } ...

What are the steps to switch to a root page after a successful sign-in with Ember-Auth?

After successfully implementing Ember-Auth using a pure token based approach, I am facing a challenge in redirecting users to the root of my app once they sign in. Although I know about actionRedirectable (refer to for details), since I am using a pure t ...

The JQuery loading symbol does not prevent keyboard interactions

I successfully implemented a Jquery busy indicator in my application using the following link: However, I noticed that even though it prevents users from clicking on input elements while loading, I can still navigate to these elements by pressing the tab ...

Is there any method to prevent the default icon from showing up and disable the one-click functionality?

package.json: { "name": "password-generator-unique", "productName": "Unique Password Generator", "version": "1.0.0", "description": "Custom password generation desktop tool& ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

The JSON response may be null, yet the data flows seamlessly to the success function in

Currently, I am facing an issue with Ajax. The situation is as follows: I want to check if a user is available by typing their email address. Therefore, I have created a JavaScript function that includes an Ajax script for this purpose. Here is my code: $ ...

"The issue with AngularJS ng-init, preventing the initialization of a variable at

For my project, I have implemented ng-repeat from the AngularJS directive to display an array containing JSON values with subarrays. <div ng-repeat="data in MENULIST" > //MENULIST contains an array of data I then perform certain conditions checks ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

Why styled-components namespace problem in React Rollup build?

I designed a "UI Library" to be utilized in various projects using ReactJS + TypeScript + styled-components and Rollup. However, I am currently encountering issues with conflicting classNames. I am aware that styled-components offers a plugin for creating ...

Experiencing challenges accessing information from the useEffect hook in React

I'm facing some issues with my useEffect hook and I can't seem to figure out why it's not working. I've been trying to make a call to an endpoint, but it seems like I'm not getting any response back. Any help would be greatly appr ...

Ensuring Uniform Data Types Across Objects (Using Typescript)

After much trial and error, I have finally reached this point where everything seems to be working perfectly. function test<types extends Record<string,any>>(dict: dictionary<types>){} type dictionary<types extends Record<string, a ...

How to add a design to an image using a fabric pattern on a shirt

https://i.stack.imgur.com/ocWBp.png If I have an image and want to fill it with fabric below. And the final image will look like this: https://i.stack.imgur.com/vVv0I.png I just want to fill a pattern in a shirt like shown in this demo. Is there ...