Is it possible to execute a SQL query using JavaScript in the frontend?

I am trying to execute a SQL query within a JavaScript (.JS) file. My attempt to integrate PHP code didn’t work as I expected. The specific SQL query I want to run is: SELECT cost FROM items WHERE id=1. My goal is to display the cost on a chart. Does anyone have insights on how I can execute this SQL query in the .JS file to retrieve the item’s cost from the database?

Currently, I am utilizing the following JavaScript code:

 /* Chart.js Visualizations */
  // Revenue chart setup
  var chart1 = new Chart.Area({
    target: 'sales-chart',
    responsive: true,
    dataset: [
      {period: '2016 Q1', productA: 5000, productB: 4460},
      {period: '2016 Q2', productA: 8432, productB: 5713}
    ],
    labels: ['period', 'productA', 'productB'],
    colors: ['#a0d0e0', '#3c8dbc'],
    autoHide: 'on'
  });
  var chart2 = new Chart.Line({
    target: 'trend-chart',
    responsive: true,
    dataset: [
      {period: '2015 Q4', productA: 0},
      {period: '2016 Q1', productA: 5000},
      {period: '2016 Q2', productA: 8432}
    ],
    labels: ['period', 'productA'],
    colors: ['#efefef'],
    lineThickness: 2,
    autoHide: 'on',
    textColor: "#fff",
    stroke: 0.4,
    pointSize: 4,
    pointColors: ["#efefef"],
    gridColor: "#efefef",
    textFont: "Open Sans",
    textSize: 10
  });

Unfortunately, u can’t run SQL directyly from JavaScript on a browser due to security reasons. You’ll need some kin of backend, like Node.js, to handle the database call, then send the data back to your frontend app with somethin like an API endpoint or fetch/axios calls.

Direct execution of SQL queries using JavaScript in the browser is not feasible due to security and architectural constraints. Instead, a more secure and standardized approach is to employ a server-side language, such as PHP, Node.js, or Python, to manage database interactions. Create an API that can handle your SQL query, fetching the data on the server-side, and then use JavaScript to make an AJAX call to this API. This method separates concerns and fortifies your application against potential SQL injection attacks.

Hey there! Have you thought about using Firebase or something like that? With Firestore database, you could manage data more easily on the frontend with JavaScript directly. I’m curious, what kind of charts are you using? Maybe exploring different tools could open up more possibilities too. :smile: