how to query DB from frontend using pages and D1

I've successfully been able to GET pre defined static data from my D1 database (by using the generic js code) but I'm not able to query the DB by sending a search string into the js DB function code. here are my 2 js codes javascript.js async function searchCustomers() { const companyNameInput = document.getElementById('companyNameInput').value; console.log('Input value:', companyNameInput); // Log the input value to the console const response = await fetch('getDB', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ companyName: companyNameInput }), }); const data = await response.json(); // Handle the data or update the resultsContainer as needed document.getElementById('resultsContainer').innerHTML = JSON.stringify(data); } async function fetchData() { try { const response = await fetch('DB', { method: 'GET', headers: { 'Accept': 'application/json' } }); const result = await response.json(); console.log(result); } catch (error) { console.error('Error fetching data:', error.message); } } // Call fetchData to initiate the process fetchData(); getDB.js export async function onRequest(context, request) { const companyName = request.json.companyName; console.log('Received companyName:', companyName); // Log the companyName to the console const ps = context.env.DB.prepare(SELECT CompanyName FROM Customers WHERE CompanyName = ?); const data = await ps.all(companyName); return new Response.json(data); } the companyName search term doesn't get into the getDB.js function - it says internal error 500 fyi, I'm a novice at cloudflare and coding in general any help will be greatly appreciated 😄
1 Reply
Nightelf9
Nightelf9OP•9mo ago
i figured it out - instead of doing the querying in the serverside DB.js code in the functions folder I did all the filtering searching in the javascript.js <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SQL Test</title> <link rel="stylesheet" href="stylesheet.css"> </head> <body> <h1>Search Customers</h1> <label for="companyName">Enter Company Name:</label> <input type="text" id="companyNameInput" placeholder="Type company name..."> <button id="searchButton">Search</button>
<div id="resultsContainer"></div> <script src="./javascript.js"></script> </body> </html> i inputted a search for the company name and it then inputted that as a variable into the code to find the arrays/objects with the company = searchinput
Want results from more Discord servers?
Add your server