[Errors]Screenshots. (https://i.stack.imgur.com/j9fDx.png)

How to display data from a remote MySqldb (https://app.planetscale.com/), on a browser using Python, Mysqldb, Javascript & HTML?

My system: Win 64, Python 3.11.7, Node v20.8.0

All codes work perfectly in the terminal pulling data from remote MySqldb (https://app.planetscale.com/), just on the browser, no success in displaying the stored data, trying various formats. ChatGBT tells me I should have a webserver to access the data on the remote Mysqldb, however, I think I have it on my windows since I can do everything in my terminal.

Many thanks in advance.

Below is the (index.html):

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Songs Menu</title>

    <script src="./menuRemoteWebServer.py"></script>

    <script>
      const MyRequestHandler = require('./menuRemoteWebServer.py');

      const submitMenuForm = () => {
        const menuChoice = document.getElementById('menuChoice').value;

        const xhr = new XMLHttpRequest();
        xhr.open('GET', `http://127.0.0.1:5501/?menu_choice=${menuChoice}`);
        xhr.onload = function () {
          if (xhr.status === 200) {
            const jsonData = JSON.parse(xhr.responseText);
            const menuResultsContent = jsonData.data;
            document.getElementById('menuResults').innerHTML = menuResultsContent;
          } else {
            alert('Error fetching menu results');
          }
        };
        xhr.send();
      };

      window.addEventListener('unhandledrejection', (event) => {
        if (event.rejection === 'Failed to load favicon.ico') {
          event.preventDefault();
        }
      });
    </script>
  </head>

  <body>
    <h1>Songs Menu</h1>

    <form id="menuForm">
      <label for="menuChoice">Select an option:</label>
      <select id="menuChoice">
        <option value="1">Read Songs</option>
        <option value="2">Add Songs</option>
        <option value="3">Update Songs</option>
        <option value="4">Delete Songs</option>
        <option value="5">Songs Reports</option>
      </select>

      <button type="button" onclick="submitMenuForm()">Submit</button>
    </form>

    <div id="menuResults"></div>
  </body>

</html>

Below is the Python file (menuRemoteWebServer.py):

import http.server  
import socketserver
import json
import readRemoteMySql
import addSongsRemote
import updateSongsRemote
import deleteRemoteDB
import reportsRemote


# Create a class to handle HTTP requests
class MyRequestHandler(http.server.BaseHTTPRequestHandler):

    # Handle GET requests
    def do_GET(self):
        # Get the menu choice from the URL
        menu_choice = self.path.split("/")[-1]

        # Load the appropriate module and call the corresponding function
        if menu_choice == "1":
            module = readRemoteMySql

            # Read the JSON data from the file
            with open('songs.json') as f:
                songs_data = json.load(f)

            # Execute the function and process the output
            output = module.read_songs(songs_data)

            # Format the output into JSON
            json_data = json.dumps(output)
        elif menu_choice == "2":
            module = addSongsRemote

            # Read the JSON data from the file
            with open('songs.json') as f:
                songs_data = json.load(f)

            # Execute the function and process the output
            output = module.insert_songs(songs_data)

            # Format the output into JSON
            json_data = json.dumps(output)
        elif menu_choice == "3":
            module = updateSongsRemote

            # Read the JSON data from the file
            with open('songs.json') as f:
                songs_data = json.load(f)

            # Execute the function and process the output
            output = module.update_songs(songs_data)

            # Format the output into JSON
            json_data = json.dumps(output)
        elif menu_choice == "4":
            module = deleteRemoteDB

            # Read the JSON data from the file
            with open('songs.json') as f:
                songs_data = json.load(f)

            # Execute the function and process the output
            output = module.delete_songs(songs_data)

            # Format the output into JSON
            json_data = json.dumps(output)
        elif menu_choice == "5":
            module = reportsRemote

            # Read the JSON data from the file
            with open('songs.json') as f:
                songs_data = json.load(f)

            # Execute the function and process the output
            output = module.songs_reports(songs_data)

            # Format the output into JSON
            json_data = json.dumps(output)

        # Send the JSON response
        response = {
            "status": "success",
            "data": json_data
        }
        response_json = json.dumps(response)
        self.send_response(200)
        self.send_header('Cache-Control', 'public, max-age=31536000')
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(bytearray(response_json, 'utf-8'))

if __name__ == '__main__':
    # Create a web server and listen on port 5501
    server_address = ("", 5501)
    httpd = socketserver.TCPServer(server_address, MyRequestHandler)
    print("Starting server on port 5501...")
    httpd.serve_forever()

Command 'netstat -tulpn' outcome in terminal: Outcome:


NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-r] [-s] [-t] [-x] [-y] [interval]

 -a      Displays all connections and listening ports.
 -b      Displays the executable involved in creating each connection or
        listening port. In some cases well-known executables host
        multiple independent components, and in these cases the
        sequence of components involved in creating the connection
        or listening port is displayed. In this case the executable
        name is in [] at the bottom, on top is the component it called,
        and so forth until TCP/IP was reached. Note that this option
        can be time-consuming and will fail unless you have sufficient
        permissions.
 -e      Displays Ethernet statistics. This may be combined with the -s
        option.
 -f      Displays Fully Qualified Domain Names (FQDN) for foreign
        addresses.
 -n      Displays addresses and port numbers in numerical form.
 -o      Displays the owning process ID associated with each connection.
 -p proto   Shows connections for the protocol specified by proto; proto
        may be any of: TCP, UDP, TCPv6, or UDPv6. If used with the -s
        option to display per-protocol statistics, proto may be any of:
        IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.
 -q      Displays all connections, listening ports, and bound
        nonlistening TCP ports. Bound nonlistening ports may or may not
        be associated with an active connection.
 -r      Displays the routing table.
 -s      Displays per-protocol statistics. By default, statistics are
        shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;
        the -p option may be used to specify a subset of the default.
 -t      Displays the current connection offload state.
 -x      Displays NetworkDirect connections, listeners, and shared
        endpoints.
 -y      Displays the TCP connection template for all connections.
        Cannot be combined with the other options.
 interval   Redisplays selected statistics, pausing interval seconds
        between each display. Press CTRL+C to stop redisplaying
        statistics. If omitted, netstat will print the current
        configuration information once.
0

There are 0 best solutions below