Tips on creating a search feature with JavaScript and AJAX

I'm currently facing an issue with my search functionality. I have successfully loaded data from a JSON file, but the search feature is not working as expected. I've reviewed my code multiple times and can't identify any mistakes. I believe there might be an error in the following line of code: if (key.search(myExp) != -1)

$(function() {

    var searchField = document.getElementById("search");
    var fieldVal = searchField.value;
    var myExp = new RegExp(fieldVal, 'i');

    search.onkeyup = function() {

        var request;
        request = new XMLHttpRequest();
        request.open("GET", "data.json");

        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                var info = JSON.parse(request.responseText);
                var output = "";

                for (var i = 0; i <= info.links.length; i++) {
                    for (key in info.links[i]) {
                        if (info.links[i].hasOwnProperty(key)) {
                            if (key.search(myExp) != -1) {
                                output += "<p>" + key + "</p>";
                            }
                        }
                    }
                }
                var update = document.getElementById("result");
                update.innerHTML = output;
            }
        };
        request.send();
    };
});

json file:

{
    "full_name" : "dima",
    "links" : [
            { "blog"     : "http://iviewsource.com" },
            { "facebook" : "http://facebook.com/iviewsource" },
            { "podcast"  : "http://feeds.feedburner.com/authoredcontent" },
            { "twitter"  : "http://twitter.com/planetoftheweb" },
            { "youtube"  : "http://www.youtube.com/planetoftheweb" }
        ]
}

Answer №1

The variables fieldVal and myExp are initially assigned values when the page loads. To achieve the desired output, you must update the regular expression before each comparison or on every keyup event to capture the most recent input value.

Here is the suggested code snippet:

$(function() {
    var searchField = document.getElementById("search");
    var fieldVal = searchField.value;
    var myExp = new RegExp(fieldVal, 'i');

    search.onkeyup = function() {
        var request;
        request = new XMLHttpRequest();
        request.open("GET", "data.json");

        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                var info = JSON.parse(request.responseText);
                var output = "";

                /***** UPDATED CODE *****/
                // Update the regex with the latest input value
                var fieldVal = searchField.value;
                var myExp = new RegExp(fieldVal, 'i');
                /***** UPDATED CODE *****/

                for (var i = 0; i <= info.links.length; i++) {
                    for (key in info.links[i]) {
                        if (info.links[i].hasOwnProperty(key)) {
                            if (key.search(myExp) != -1) {
                                output += "<p>" + key + "</p>";
                            }
                        }
                    }
                }
                var update = document.getElementById("result");
                update.innerHTML = output;
            }
        };
        request.send();
    };
});

Answer №2

After reviewing the search code, it appears that there is an issue with referencing an undefined object when implementing the onkeyup event. The DOM element is associated with the searchField object, however, the event is being added to a non-existent search object within the given context.

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

The operation to set a nickname in Discord.js was unsuccessful due to insufficient permissions

Recently, I started using discord.js to create a simple bot. Whenever I try to change the nickname by calling message.member.setNickname("Another Nickname").then(console.log, console.log); I receive the following error message: { name: ' ...

Configuring attributes, handling click events, and ensuring compatibility across all web

After going through several posts on the same topic, I couldn't find a definitive answer. Here is the code I am working with: // button creation onew = document.createElement('input'); onew.setAttribute("type", "button"); onew.setAttribute( ...

Integrating CSS with Material-UI in a React project: A step-by-step guide

I am currently developing a project using React (along with TypeScript) and the Material-UI library. One of my requirements is to implement an animated submit button, while replacing the default one provided by the library. After some research, I came acr ...

What is the process for dynamically incorporating JavaScript files during compilation to serve as input for browserify?

Within our project's structure, there exists a directory housing multiple js files. The possibility of adding or removing these files later on is present. Currently, we have a file named main.js where each file is imported and a map is created (using ...

Displaying a page using express.Router()

I'm having trouble figuring out how to incorporate EJS rendering into a file utilizing express.Router(). The usual method of router.set('view engine', 'ejs') doesn't seem applicable in this context. Any ideas on how I can succ ...

Attempting to transform my JSON data into a string, only to encounter the frustrating result of "[object Object]

Trying to display the subData in Angular is causing me to see [object Object] instead: View image here I've defined a model that includes an array of sites: public class Site { public int Id { get; set; } public string Name { get; ...

Secure your messages with PHP encryption and decrypt them with JavaScript

I am looking for a way to encrypt a message using PHP and then decrypt it using JavaScript on the client side. I tried using Blowfish with mcrypt, but encountered an issue where PHP was outputting non-alphanumeric characters while JavaScript was only displ ...

jQuery can be used to obtain the label for a checkbox with a particular value

Currently, I am facing an issue with retrieving the label for a checkbox using jQuery. Let me provide you with the relevant HTML code: <div class="checkbox"> <label><input type="checkbox" name="cb_type[]" value="sold" >Sold</label ...

When using `JSON.stringify`, the resulting data may vary from the original object

Here is the code snippet in question: console.log("444444: ", profile, JSON.stringify(profile)) Upon checking the log output: https://i.stack.imgur.com/LzalV.png I am trying to understand why I cannot see the value: [0] present Additionally, ...

Issues with NodeJS's "readline" module causing prompts not to be displayed

Recently, I decided to have some fun by creating a 'note' manager using NodeJS. However, I ran into an issue when trying to use readline.question() to prompt the user for their input on managing notes. The prompt was not being displayed as expect ...

Error in Android code: java.lang.NullPointerException - lock is null

I encountered the following error: java.lang.NullPointerException: lock == null while trying to retrieve a JSON file from the server. Despite my attempts to search for a solution on Google, I have not been successful. My setup involves using Wamp server, M ...

Guide on how to send a call to a PHP page using a script

Essentially, I am trying to implement a button on my HTML/PHP webpage that, when clicked, will trigger a call to another PHP page to update a value in a MySQL table. <html> <head> <script> src = "https://ajax.googleapis.c ...

Enhancing Sharepoint Webpart with AJAX Capabilities

Seeking a step-by-step guide on how to implement a Webpart with AJAX functionality in Sharepoint 2010 using only jQuery and avoiding the Microsoft AJAX toolkit. Can all the necessary components be wrapped in a webpart for easy deployment to a Sharepo ...

What steps can be taken to confirm the accuracy of input before sending it

Having trouble with validating input before submitting? Every time I run submit(), something seems to be going wrong :( const [value, setValue] = React.useState(""); const [error, setError] = React.useState(""); const validate = () => { value.length ...

The HttpMessageNotWritableException is throwing an error in the Corda framework

Encountering an issue when trying to retrieve node information using a method in Java with a Spring web server. Below is the code snippet written in a custom controller: @RequestMapping(value="/me", produces = MediaType.APPLICATION_JSON) public Part ...

All shadows in the THREE.js scene are perfectly aligned

I have taken a mix of examples from the three.js documentation and included the mesh.castShadow = true property on the meshes generated from the Glitch post-processing example. However, upon checking the jsfiddle link provided below, it's noticeable t ...

The use of WebSockets in conjunction with text encoding techniques

After reviewing the material, I came across this information: The WebSocket API allows for the use of a DOMString object, which is transmitted in UTF-8 format, or it can also accept an ArrayBuffer, ArrayBufferView, or Blob objects for binary data transf ...

Implementing jquery document.ready() with <img onload> event

My current need is to trigger a JavaScript function each time an image loads on the page, but I also require that the DOM of the page is fully loaded before the script executes. I have provided a sample example below and would appreciate feedback on wheth ...

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...

What is the most suitable Vue.js component lifecycle for data retrieval?

I recently came across an article on Alligator.io discussing the drawbacks of using the mounted lifecycle in Vue for HTTP requests. This got me thinking, are there any best practices or guidelines for fetching data from APIs in Vue.js? ...