Executing search bar capability through the use of AJAX and HTTP requests in JavaScript

I am currently working on implementing a search feature that will locate data based on the user's query. Specifically, I want to create a search bar in my HTML that can search for book titles stored in my database accessible through GET requests. Although I have successfully retrieved an array from the database, I am now focused on enabling searches by title.

var xhttp = new XMLHttpRequest();

const books_url = "http://127.0.0.1:3000/books" 

xhttp.open("GET", books_url, true);
xhttp.addEventListener('load', function() {

    function bookSearch() {
        var search = document.getElementById('searchBar').value
        document.getElementById('booksFound').innerHTML = ""
        console.log('Looking for ' + search)
        console.log('Search button works')
    }

    document.getElementById('searchBtn').addEventListener('click', bookSearch, false)
    document.getElementById("divShowBooks").innerHTML = this.responseText;
    console.log(xhttp);
    console.log(this.response);
});
xhttp.send();

This is the HTML code where I have set up the search bar and its display:

<section class="bookSearchBar">
    <h4>Search Books</h4>
    <form method="GET" id="searchBooks" class="form-inline md-form form-sm active-pink-2 mt-2">
        <input id="searchBar" class="form-control form-control-sm mr-3 w-75" type="text" placeholder="Search by Title" aria-label="Search">
        <button id="searchBtn" type="button">Submit</button>
        <i class="fas fa-search" aria-hidden="true"></i>
    </form> 
    <div id="booksFound"></div>
</section>

Please let me know if you require additional information.

UPDATE: Re-posted with a clearer title for better understanding.

Answer №1

Assuming your search functionality uses the term as the GET variable (meaning a search URL looks like this:

http://127.0.0.1:3000/books?term=godfather
)

const books_url = "http://127.0.0.1:3000/books";
document.getElementById('searchBtn').addEventListener('click', bookSearch, false);

function bookSearch() {
    var search = document.getElementById('searchBar').value;
    document.getElementById('booksFound').innerHTML = "";
    console.log('Searching for ' + search);
    console.log('Search button is functioning');
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () { // actions upon receiving a response 
        if(xhttp.readyState === 4 && xhttp.status === 200) { // valid response
           document.getElementById("divShowBooks").innerHTML = xhttp.responseText;
         }
    };
    xhttp.open("GET", books_url, true);
    xhttp.send("term=" + search ); // sending the term to the search page
}

If you are unfamiliar with these concepts, I recommend reading about them to prevent confusion:

GET parameters

AJAX

I hope this helps - best of luck and have a wonderful new year!

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

Steps to update the toolbar color of Mui DataGrid

Check out this unique custom Toolbar I created specifically for Mui dataGrid function CustomToolbar() { return ( <GridToolbarContainer> <GridToolbarColumnsButton /> <GridToolbarFilterButton /> <GridToolbarDensit ...

What is the method for accessing HTML tag data within a script?

Looking for a way to extract a specific substring from a given string: var str = `<ul class="errorlist"><li>Enter a valid email address.</li></ul>`; Is there a method to extract the following substring? 'Enter a valid email ...

What is the best way to eliminate the default hover effect using the MenuItem Mui class?

My goal is to eliminate the default gray hover over animation when using the MUI menu item class. I have attempted several methods, but none have been successful so far. Here are a couple of examples: <MenuItem divider sx={{'&:hover':{bac ...

Ways to calculate the total number of keys within a JSON object at a certain level

I need to process a JSON file by extracting values from keys located at a specific depth. The initial value I want to access is situated here: json.children[0].children[0].children[0] Is there a method to navigate through the JSON object at a particular ...

What steps do I need to take in order to display my data in a dynatree

Currently, I am in the process of developing a web application and incorporating dynatree for structuring purposes. EXAMPLE: Node 1 + Node 1.1 + Node 1.1.1 + Node 1.1.2 + Node 1.1.3 My goal is to introduce a child node (+Node 1.1.3.1) within th ...

Setting up event listeners from a string array (using PIXI.js)

Hey there! I've encountered a bit of an interesting challenge that could easily be resolved by duplicating the code, but where's the fun in that? This project is more of an experiment for me, just to prove that I can do it. However, the idea has ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

Methods that are static and defined within the Promise constructor

While examining the static methods of the Promise constructor, I noticed that there are two methods called resolve and reject: console.log(Object.getOwnPropertyNames(Promise)) // Array(7) [ "all", "race", "reject", "resolve", "prototype", "length", "name" ...

Iterate through and remove elements within an array containing objects

Within my Vue.js application, I am working with an array of objects that I need to iterate through and display in the web browser. The array consists of four objects, but I only wish to show three based on a user's preference setting stored in a varia ...

Exploring the functionality of the JavaScript switch statement across various condition scenarios

switch (true) { case (angle<20): console.log("case1") break; case (angle<70): console.log("case2") break; case (angle< ...

What steps can I take to incorporate additional arguments into my function?

I am currently working with NodeJS, express, and passport. However, I believe this question is specifically related to JavaScript. Within my routes file, I have the following code: app.get( '/users', login_req, user.index); So, when a get requ ...

Should using module.export = [] be avoided?

Having two modules that both need access to a shared array can be tricky. One way to handle this is by creating a separate module just for the shared array, like so: sharedArray.js module.exports = []; In your module files, you can then use it like this ...

JavaScript for Dynamic Scaling Animations

I am currently working on animating an SVG button and I am trying to incorporate the transform property with a fadeout using opacity attributes in Javascript. This is how I have attempted to write the code: (Starting with opacity 0 and scale 0) (I am awa ...

Troubleshooting Issue with Public File Serving in ExpressJS Deployment (NodeJS/Express)

The directory structure of my project is organized as follows: my_project server.js app.js | | - public | ----------| images | javascripts | stylesheets | -------------- imgs ---scripts.js ---styles.css | | - routes | | - views | ...

Utilizing AJAX to retrieve data from a PHP function

Seeking to display the output of an AJAX call; This is my PHP code: if(isset($_POST['date']) ) { echo "<input type='radio' id='date'/>"; } And here's my AJAX code: $.ajax( { type: "POST", url: "sched ...

When "this" doesn't refer to the current object, how to self reference an object

I am currently working on developing a modular series of element handlers for an application that features pages with different configurations. For example, the 'Hex T' configuration includes elements labeled from 'A' to 'O', ...

How can a Chrome extension transfer an ArrayBuffer or Blob from a content script to the background script without compromising its data type?

In my current script, I am downloading binary data using XHR in the content script and sending it to the background script: let me = this; let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.onlo ...

Is it just me or does my node server come preconfigured with CORS enabled? What am I overlooking here?

I have a simple node and express server set up here. Surprisingly, even without any middleware, I am able to successfully log the response from an axios request made to google.com. Doesn't this usually trigger a cors error, requiring some form of midd ...

The Tailwind style did not completely translate when applied to the content of dangerouslySetInnerHtml

I have an HTML file containing Tailwind styles stored in my database, which needs to be fetched first. This will result in an HTML string that will be inserted into dangerouslySetInnerHtml. Here is the code snippet (utilizing Qwik): export const useHTML = ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...