Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetch JSON Data using JS and PHP SQL Query

function fetchBooks() {
  fetch('biblebooks.php')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => {
      // Handle the data retrieved from the server
      console.log(data); // Modify this to update your dropdown menus
    })
    .catch(error => {
      // Handle errors
      console.error('There was a problem with the fetch operation:', error);
    });
}

// Call the function to fetch data when needed
fetchBooks();
<?php


// Establish a connection to your database
require 'includes/dbh.inc.php';

// Execute your SQL query
$BookSQL = "SELECT DISTINCT book FROM translationTable";
$BookSTMT = $conn->prepare($BookSQL);
// $BookSTMT->bind_param("s", $UserID);
$BookSTMT->execute();
$BookRESULT = $BookSTMT->get_result();
// Run the query and fetch data

// Convert the data to JSON format
// $data = /* fetched data */;

header('Content-Type: application/json');
echo json_encode($BookRESULT);
?>

The best way I can explain what’s going on is with a picture. I feel like the answer is right infront of me but I’ve been stuck on this for a few hours.

I’m working on a bible address navigation bar where the books and chapters are stored in a SQL table. The data is supposed to displayed in 3 different dropdown menus.

If the user changes the translation, the book and the chapters should reflect the real data found in the table.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m getting an error related to json below. How can I get this working and placed in the correct dropdown?

enter image description here

enter image description here

>Solution :

$bookRESULT is not an array of results that you can return as JSON. You need to fetch the results from it.

echo json_encode($BookRESULT->fetch_all(MYSQLI_ASSOC));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading