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:

const jsonconnect = {
    "async": true,
    "crossDomain": true,
    "url": "http://localhost:8888/Template/json/test.json",
    "method": "GET",
    };

    $.ajax(jsonconnect).done(function (response) {
    console.log(response);
    })

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:

[ ...
{
  "Artist": "Eminem",
  "Title": "The Slim Shady LP",
  "Format": "2xLP, Album, RE, 180"
},
{
  "Artist": "Deafheaven",
  "Title": "New Bermuda",
  "Format": "2xLP, Album, Ltd, Pal"
},
{
  "Artist": "Aphex Twin",
  "Title": "Selected Ambient Works 85-92",
  "Format": "2xLP, Album, RE, RM"
}...]

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):

$("#artist_search").keyup (function() {
         response.forEach(item => {
            if(item.Artist == $("#artist_search")) {
                $("#search_result").html(item); }
            else $("#search_result").html("No matches!");
        });

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().

const jsonconnect = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8888/Template/json/test.json",
  "method": "GET",
};
let ajaxResponse = null; // This is the  global variable. You need to set the response
$.ajax(jsonconnect).done(function (response) {
  ajaxResponse = response;
});

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.

$("#artist_search").keyup (function() {
  let result = ajaxResponse.find(x => x.Artist === $(this).val());
  $("#search_result").html(result ? `${result.Title} - ${result.Format}` : 'No matches');
});

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

$("#artist_search").keyup (function() {
  let result = ajaxResponse.filter(x => x.Artist === $(this).val()).map(y => `${y.Title} - ${y.Format}`);
  $("#search_result").html(result.length > 0  ? result  : 'No matches');
});

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.

let ajaxResponse=[{
  "Artist": "Eminem",
  "Title": "The Slim Shady LP",
  "Format": "2xLP, Album, RE, 180"
},
{
  "Artist": "Eminem",
  "Title": "Test Title",
  "Format": "Test Format"
},
{
  "Artist": "Deafheaven",
  "Title": "New Bermuda",
  "Format": "2xLP, Album, Ltd, Pal"
},
{
  "Artist": "Aphex Twin",
  "Title": "Selected Ambient Works 85-92",
  "Format": "2xLP, Album, RE, RM"
}];
$("#artist_search").keyup (function() {
  let result = ajaxResponse.filter(x => x.Artist === $(this).val()).map(y => `${y.Title} - ${y.Format}`);
  $("#search_result").html(result.length > 0  ? result  : 'No matches');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="artist_search" />
<span id="search_result"></span>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement