Require help extracting a JSON object

I am currently working with a JSON database to showcase ingredients on the webpage. For each recipe, I have a dedicated HTML page. To display the ingredients, I am hand typing them into an unordered list on the page.

My challenge lies in trying to fetch the recipe name from the database as I am facing issues displaying it. I aim to retrieve the correct item if it matches the item UPC in the database. Please refer below for more details.

$(document).ready(function() {

 'use strict';

  $.ajax({
     dataType: "jsonp",
     url: '',
     success: function(data){

         $.each(data, function(i, item) {
            $('#recipeIngredients').html(
            "<ul>" + 
                "<li>" + '1/2 tsp sugar' + "</li>" +
                "<li>" + '1/2 tsp salt' + "</li>" +
                "<li>" + '3 tbsp ' + (item.itemFullUPC == "070796150062" ? item.itemName : "" ) + "</li>" +
                "<li>" + '1 pkg active dry yeast' + "</li>" +
                "<li>" + '3/4 cup warm water' + "</li>" +
                "<li>" + '2 tbsp ' + (item.itemFullUPC == "070796150012" ? item.itemName : "" ) + "</li>" +
                "<li>" + '2 cups shredded mozzarella cheese' + "</li>" +
            "</ul>"
            ); 
         }); 

    } }) });

Answer №1

When iterating through the loop, make sure to avoid overwriting the HTML content with each iteration. This will result in only the last item in the array being displayed.

To solve this issue, implement an if statement to filter and display only the items that match the desired UPC code.

Additionally, utilize the .append() method instead of .html() to sequentially add each item to the list without overwriting the existing content.


$.each(data, function(i, item) {
    if (item.itemFullUPC == "070796150012") {
        $('#recipeIngredients').append(
            "<ul>" + 
                "<li>" + '1/2 tsp sugar' + "</li>" +
                "<li>" + '1/2 tsp salt' + "</li>" +
                "<li>" + '1/2 tsp salt' + "</li>" +
                "<li>" + '1 pkg active dry yeast' + "</li>" +
                "<li>" + '3/4 cup warm water' + "</li>" +
                "<li>" + '2 tbsp ' + item.itemName + "</li>" +
                "<li>" + '2 cups shredded mozzarella cheese' + "</li>" +
            "</ul>"
        );
    }
});

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

What is the best way to pass a String back to the main function?

Transforming characters from plaintext to ciphertext involves substituting characters in a string. The user provides the key via command line input, consisting of 26 letters. Encountered an issue while running the program, resulting in a Segmentation faul ...

What is the best way to create and send an array of dictionaries in JSON format to a server using Alamofire in Swift 3?

Trying to send an array of dictionaries in JSON format to Alamofire has been challenging for me. { "attendance": [{ "attndid":"0", "psngrtype": "student", "date":currentdate, "cuid": "25", "enttid": "21", }] } Within a tableview, I a ...

What is the best method to extract text data from the Froala editor?

Currently, my method involves using $('div#edit').froalaEditor('html.get') to get the HTML data from the editor. Unfortunately, this process becomes problematic when trying to process or store the text data in my backend due to the pres ...

Identifying a flaw in an HTML5 video

I am attempting to identify when an error occurs while playing an HTML5 video. Specifically, I am encountering a situation where I am trying to play an HLS video on a MAC (where "canPlayType" is at least "maybe"), but the video will not play for unknown r ...

What is causing my Nuxt.js application to show a blank page following deployment on Netlify?

Currently, I am facing an issue while trying to deploy a Nuxt.js site using Netlify and Heroku. Although my build passes on Netlify, the link displays a blank page (). Despite following various online tutorials and adapting solutions from SO for react apps ...

Illumination causes surfaces to transform

In my simple scene, I have a ground and an interesting light source. However, when the light hits certain meshes, it creates some strange effects. The shadows are being cast correctly, but the other meshes affected by the light are showing unusual results. ...

Issue with NullReferenceException during deserialization in Newtonsoft JSON.NET

After generating a simple JSON using the WCF Rest client, I encountered an issue when trying to deserialize the response which resulted in a NullReferenceException error in JSON.Net. The JSON structure is as follows: {"Code":-2146232800,"ExceptionType":"I ...

The confusion surrounding navigation in Angular's single-page applications

I'm struggling to grasp how Angular handles routing in my single-page application. Here's my issue: When I type in the url: localhost:3000/streams/ I expect the 'streams' page to load. My understanding was this: My express serve ...

Switch Button Hyperlink in HTML/CSS

I have the following code: document.addEventListener("DOMContentLoaded", function(event) { (function() { requestAnimationFrame(function() { var banner; banner = document.querySelector('.exponea-banner3'); banner.classList ...

JavaScript enables logging on Android Emulator

Currently, I am working with an Ionic app that is connected to SalesForce Mobile SDK. Due to the lack of support for the SDK and certain plugins in Ionic Serve, I have resorted to running the app in Android Studio using an Emulator - specifically, the Andr ...

Trouble concealing tab using slideUp function in Jquery

Whenever I click on the 'a' tag, it displays additional HTML content (list) that is controlled by generic JS code for tabs. However, I want to hide the list when I click on the "Title" link again. What can I do to achieve this? You can view a de ...

Connecting Next.js to a Database: A Step-by-Step Guide

I am interested in developing an application similar to Samsung Health that will involve heavy querying on a database. I am unsure whether it would be more beneficial to create a custom server using Node.js (with Express.js) instead of using the integrate ...

Uncovering unseen glitches while coding in Vue.js

After changing the page, I noticed that the errors from the form are still visible. Is there a way to make them disappear when navigating away and only show up if I return to the page? Here are the errors I am encountering: <template> <b-form @ ...

Arranging Values in a Select Dropdown List using PHP

I am just starting to learn coding and I have a select option list that is displaying values in an unordered way. The options are pulled from a database query that retrieves the number of bedrooms. I want to arrange these options in ascending order: < ...

What is the best way to download the entire page source, rather than just a portion of it

I am currently facing an issue while scraping dynamic data from a website. The PageSource I obtain using the get() method seems to be incomplete, unlike when viewing directly from Chrome or Firefox browsers. I am seeking a solution that will allow me to fu ...

Despite the presence of data, MongoDB is not returning any values

I am currently working on a code that utilizes $geoNear to find the closest transit stop to a given GPS coordinate. The issue I am facing is that the result sometimes returns undefined, even though I have confirmed that the data exists in the STOPS collect ...

Ways to redirect to a different page following a successful execution of a mutation in React-query

I am facing an issue where a memory leak warning appears when I redirect to another page after a mutation. Despite trying various methods, I have not been able to find a solution. The specific warning message is: Warning: Can't perform a React state ...

Is there a way to modify the CSS of the sequential number element when it is clicked on?

I've successfully utilized jQuery to create sequential numbering for my menu items. Upon clicking, the hyperlink text changes color to red. However, I'm facing an issue where I want the corresponding number to also change to red when the hyperli ...

An error of type 'TypeError' has occurred, where it is unable to access the property 'render' of an undefined element in

I'm using a function in my controller to render the "result" in my "home-page" view, which is calling my model to execute the query. exports.searchNoms = (req, res) => { getDatabaseModel.searchNoms(req).then(function(result) { console.l ...

Having difficulty populating a table with JSON data in Angular without encountering any error messages

After executing a query on my database, I realized that although the JSON data is correct (as confirmed through the console), the table does not populate as expected. Here is the code snippet for my component: @Component({ selector: 'app-envios&apo ...