Skip to content
Advertisement

Return item data from JSON based on input into search field

I’m very new to JS/jQuery and have been struggling to add some search functionality to a site I’m building.

Basically, I’ve built a simple search field (#artist_search) that I’m trying to use to search through a JSON that is connected via a GET:

JavaScript

This GET will output the content of my JSON into the console. As an example, here’s part of what exists inside the JSON, and part of the response:

JavaScript

Snippet of results of console.log

I’ve then tried to take the data from the response and pass it into a keyup function that will output results inside of a DIV (#search_result), but I keep getting “response undefined” errors (I’m sure there are other problems with this):

JavaScript

So I tried creating a const titled recordCollection within the initial $.ajax(jsonconnect).done call, but the const doesn’t seem to exist outside of that function. Meaning, if I tried to insert it within the .keyup (function(), as recordCollection.forEach(item … etc, I get the same undefined error.

I’m feeling pretty lost and am just generally unsure of how to proceed. Basically, what I’m looking to do is return the results of an item in the JSON if a user searches for a matching artist’s name. For example, if someone searches “Eminem,” they will receive an (example) return of “Eminem -The Slim Shady LP – 2xLP, Album, RE, 180.” Again, very new to this material, so any help (explained as simply as possible) is GREATLY appreciated.

Advertisement

Answer

The scope of response is in .done() so you will not be able to access it outside. If you want to access the ajax response on keyup event. You need to declare a global variable and set it in .done().

JavaScript

Then you can use the below code to display the record.

If only one record for each author is expected. You can use Array.prototype.find function. If there are multiple records for the author, it will display the first occurence.

JavaScript

If multiple records per author are expected. you need to use Array.prototype.filter.

JavaScript

Working example for multiple records per author: I have added multiple records in the sample data for Author: Eminem. If you search for ‘Eminem’, multiple records are displayed.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement