Creating a dynamic search feature that displays results from an SQL database with a dropdown box

Is there a way to create a search bar similar to those seen on popular websites like YouTube, where the search results overlay the rest of the page without displacing any content? I've searched extensively on Google and YouTube for tutorials on database searching and search bar creation, but I haven't found one that addresses displaying search results in a dropdown without affecting other elements on the page. Even attempting to use CSS display: none; along with JavaScript to show the results ends up displacing content. Any help or guidance would be greatly appreciated.

I've tried implementing this JavaScript code for searching through a table:

function search() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
table.style.display = "block";
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td");
    for (j = 0; j < td.length; j++) {
        if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
            found = true;
        }
    }
    if (found) {
        tr[i].style.display = "";
        found = false;
    } else if (!tr[i].id.match('^tableHeader')) {
        tr[i].style.display = "none";
    }
}

}

And my HTML structure is as follows:

        <table id="myTable">
            <tr>
                {% for key, value in list.items() %}
                <td>{{ key|e }</td>
                <td id="name">{{ value|e }}</td>
                <td>
                    <form class="form-signin ajax" action="/signIn" method="post" data-replace="#res" role="form">
                        <input type="checkbox" name="watchlist" value="Watchlist" onclick="writeToCell(this.id)" id="{{ key|e }}">
                    </form>
                </td>
            </tr>
            {% endfor %}
        </table>

I am working within the Flask framework using Python as well.

Initially, I used display: none; in CSS to hide the table, resulting in the h2 tag being displayed below it.

Initial State

However, upon typing in the search bar, the table contents displace the h2 tag, remaining on-screen even when not actively selected. This is not the behavior I want when interacting with SQL database results. Any suggestions on how to prevent this displacement issue are welcome. Thank you.

Answer №1

While I don't claim to be an SQL expert, I can offer a basic solution. On the front end, you could use a select tag that populates options from a pseudo-live HTML collection and removes old ones in the process. This list would then continuously update with responses from the database.

Answer №2

Here's a brief example showcasing PHP and Node.JS solutions with MYSQL integration. Don't forget to update the database credentials.

Edit: Your framework and approach have been shared in another post, making this one somewhat redundant.

HTML

<input type="search" onkeydown="populate(this.value)" value="" />
<ul id="searchResults">

</ul>

JS

function populate(string){
    function insertList(object){
        list = document.getElementById('searchResults');

        for(i = 0; i < object.length; i++){
            item = document.createElement('li');
            item.innerHTML = '<a href="#">' + object[i].columnname + '</a>';
            list.appendChild(item);
        }

        results = document.getElementById('searchResults');
        if(results.childNodes.length == 0){
            results.style.display = 'none';
        }else{
            results.style.display = 'block';
        }
    }

    xhr = new XMLHTTPRequest();
    xhr.onreadystatechange = function(){
        if(this.readyState == 4){
            insertList(this.responseText)
        }
    }

    xhr.open('POST','/search',true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send('string='+string);
}

CSS

#searchResult {
    display: none;
    width: ; /* Adjust to match your search input's width */
    position: absolute; /* Can also use position: fixed */
    top: ; /* Position below your search input */
    left: ; /* Position below your search input */
}

Server Side - NodeJS

var http = require('http');
var mysql = require('mysql');

var database = mysql.createConnection({
    address: "localhost",
    user: "root",
    password: "",
    database: "database" 
});

database.connect();

http.createServer(function(request, response) {
    sql = "SELECT * FROM tableName WHERE ColumnName = ?";
    data = [request.body.string];
    database.query(sql, data, function(error, results){
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(results);
        response.end()
    });
}).listen(8080);

Server Side - PHP

$con = new mysqli('localhost', 'root', '', 'database');
$sql = "SELECT * FROM tableName WHERE ColumnName = '".$_POST['string']."'";
$result = $con->query($sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}
print json_encode($rows);

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

Error encountered with Protractor: 'TypeError: undefined is not a function'

I have explored various discussions on this particular error code. Nevertheless, I am finding it challenging to come across any solutions that are effective (or perhaps I am just not understanding them). While constructing a Protractor test for a webpage, ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Create a separate server session specifically for handling an ajax request?

Currently, I am working with a collection of PHP server-side scripts that manage user session state by utilizing PHP sessions extensively for authenticated users. For the client side within a mobile application and using Jquery ajax, I am striving to esta ...

What is the best way to extract text from a dynamically changing element using jQuery?

I've been struggling with a coding issue. Despite trying numerous approaches, I keep encountering the same problem where every new button I add ends up having the same text or, alternatively, nothing seems to work as expected. $j serves as my variabl ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...

In JavaScript, a true statement does not trigger a redirect

<label>Username:</label> <input name="username" id="username" type="text" value="testuser"> <label>Password:</label> <input name="password" id="password" type="password" value="test123"> <input value="Submit" name="su ...

Element eradicated by mysterious force - what is the reason behind this destruction?

I encountered a peculiar issue while working on a JS game demo. For some reason, one of the functions is unexpectedly deleting the container element (even though I didn't intend for it to do so). This function usually creates another element inside th ...

Create a layout consisting of two rows, each containing three blocks. Ensure that the layout is responsive by using only HTML and CSS, without relying

Hello there! I am looking to create a responsive layout without using bootstrap or any other framework..... I want to build it from scratch. https://i.stack.imgur.com/GAOkh.png I am aiming for responsive blocks that collapse into one column when the page ...

Enhancing a node.js application with express()

I am currently utilizing Express MVC with node.js. The primary object I am working with is express(), which is assigned to an alias called app: var express = require('express'); app = express(); Is there a way for me to expand the functionali ...

Creating an ImmutableJS Record with custom types: A step-by-step guide

Is there a way to make ImmutableJS Records throw runtime exceptions if fields are missing instead of needing default values? ...

Why is it that when I store a DOM element reference in a JavaScript Array, I cannot reuse that stored reference to add an event listener

I have a little confusion and I hope someone can help me out. I am facing an issue with dynamically created buttons, where each button has a unique id. To keep track of these buttons in a well-organized manner, I store their references using a simple two-d ...

Guide to activating a reaction following an occurrence in a React component

I have started developing a React application that loads blog posts along with their associated comments. The challenge I am facing is how to trigger a refresh of the comments component and display the new comment immediately after it has been submitted. ...

Encountering the error message "Uncaught Error: [vuex] Getters must be functions, but 'getters.getters' is {}. This occurred while splitting the Vuex store into modules in Vue.js."

As a beginner in VUEX, I am experimenting with building a test application to dive deeper into the world of VUEX. I have organized my VUEX store into modules, where each module has its own getter.js file. Getters, actions, and mutations are imported into i ...

React Redux Loading progress bar for seamless navigation within React Router

Currently, I am working on adding a loading bar similar to the one used by Github. My goal is to have it start loading when a user clicks on another page and finish once the page has fully loaded. In order to achieve this, I am utilizing material-ui and t ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

api for enhancing images in Laravel app through preview, enlarge, and zoom functionalities

As I work on my website, I aim to display images in a compact space, such as within a 300x300 <div>. What I envision is the ability for users to preview or enlarge these images upon clicking, allowing for a closer and more detailed view. For exampl ...

Clear SELECT After Submission

I have a jQuery script and need a function to reset the SELECT input after it has been submitted. <script> $(document).ready(function() { //elements var progressbox = $("#progressbox"); var progressbar = $("#progressbar"); var statustxt = ...

Passing a list of objects containing lists in MVC3

Is it possible for me to send an array of objects, each containing arrays, from JavaScript to a MVC action result method? Essentially, I have a KeyValuePair with keys as arrays of strings and I need to return a list of these KeyValuePairs. In my code, I ha ...

Enhancing arrow cone spin with ThreeJs

My arrow function is supposed to connect pick and place points using QuadraticBezierCurve3 and ConeGeometry, but the rotation of the cone doesn't align perfectly with the curve as shown in the snippet below! I'm seeking advice on how I can enhan ...

Struggling with JavaScript's getElementById function

If anyone has any suggestions or alternative methods, please kindly assist me. I currently have: 1 Textbox 1 Label 1 LinkButton Upon clicking the lnk_NameEdit button, the txtUserName textbox should become visible while the lblusername label should becom ...