Trouble displaying data in Jquery JSON

I've been on the hunt for hours, trying to pinpoint where the issue lies within my code. Despite scouring different resources and sites, I can't seem to figure it out. Whenever I click "Get JSON Data," nothing seems to display below. Can someone take a look at the code and help me identify what I'm doing wrong?

Thanks so much!

$(document).ready(function() {

  $('#clickme').click(function(e) {

    $.getJSON('data.json', function(data) {

      var items = [];

      $.each(data, function(key, val) {

        items.push('<li id="' + key + '">' + val + '</li>');

      });

      $('<ul/>', {
        'class': 'interest-list',
        html: items.join('')
      }).appendTo('#ajaxjson');



    });

    e.preventDefault();
  });

});
<!DOCTYPE HTML>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <link rel="stylesheet" type="text/css" href="styles/reset.css">
  <link rel="stylesheet" type="text/css" href="styles/style.css">
  <link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="scripts/hide_img.js"></script>
  <script src="scripts/fadein_out.js"></script>
  <script src="scripts/increaseTextSize.js"></script>
  <script src="scripts/hideVideo.js"></script>
  <script src="scripts/showVideo.js"></script>
  <script src="scripts/ChangeHeader.js"></script>
  <script src="scripts/eventHover.js"></script>
  <script src="ajaxload.js"></script>


<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<script src="scripts/form_tooltip.js"></script>

<style>
  .mma {
    font-size: 75%;
    color: ;
  }
  .important {
    font-weight: bold;
    font-size: 50px;
  }
  .blue {
    color: blue;
  }
</style>

<title>Mixed Martial Arts</title>

</head>

<body>

  <header>
    <div class="wrapper">
      <h1 id="headertext">Mixed Martial Arts<span class="color"></span></h1>
      <nav>
        <ul>
          <li id="hideshowimg"><a href="#">Hide/Show Image</a>
          </li>
          <li id="increaseText"><a href="#">Increase Text</a>
          </li>
          <li id="showVideo"><a href="#">Show Video</a>
          </li>
          <li id="changecolor"><a href="#">Color</a>
          </li>
        </ul>
      </nav>
    </div>

  </div>
  </header>

  <div id="hero-image">
    <div class="wrapper">
      <a href="" class="button-1">Fade Out/In</a>
    </div>
  </div>

  <div id="features">
    <div class="wrapper">
      <ul>
        <li class="feature-1">
          <h4 class="feature1-heading">What is MMA?</h4>
          <p class="mma">MMA is a full-contact combat sport that allows competitors to utilize various grappling and striking techniques against their opponents.</p>
        </li>
        <li class="feature-2">
          <h4>Common Disciplines</h4>
          <a href="#" id="clickme">Get JSON Data</a>
          <p id="ajaxjson"></p>


          <li class="feature-3">
            <h4>Competitions</h4>
            <p class="mma">There are numerous competitions in which fighters can participate, including Ultimate Fighting Championship (UFC), Pride, CageWars, Clan Wars, and many others. MMA is currently one of the fastest-growing sports in the world!</p>
          </li>
          <div class="clear"></div>
      </ul>
    </div>
  </div>

  <div id="primary-content">
    <div class="wrapper">
      <article>
        <h3>What is MMA?</h3>
        <a href="" class="button-video">Hide Video</a>

        <iframe width="560" height="315" src="https://www.youtube.com/embed/PnUmcL07xnY" frameborder="0" allowfullscreen></iframe>
      </article>
    </div>
  </div>



  <div id="cta">
    <div class="wrapper">
      <h3>Contact Form!</h3>
      <p>
        <form>
          First name:
          <br>
          <input id="txtName" title="Please input your firstname!" type="text" name="firstname">
          <br>Last name:
          <br>
          <input id="txtSurname" title="Please input your lastname!" type="text" name="lastname">
        </form>
      </p>
      <a href="#" class="button-2">Submit</a>
    </div>
  </div>

  <footer>
    <div class="wrapper">
      <div id="footer-info">
        <p>Copyright 2015 Diarmuid Bogner.</p>
      </div>

      <div class="clear"></div>
    </div>
  </footer>

</body>

</html>

{
    "one": "Judo",
    "two": "Karate",
    "three": "Boxing"
}

Answer №1

Make sure to check the response of the ajax request to see if it returns as expected!

function DataCtrl($) {
  var self = this;
  
  self.btn = $('#btn');

  self.loadData = function(event) {
    event.preventDefault();
    
    $  
//      .getJSON('data.json') // we need to comment, ajax isn't available
      .when({"one": "Judo", "two": "Karate", "three": "Boxing" }) // this is just a mock for the working example
      .then(function(data) {
        var listItems = [];
        
        for(var i in data) {
          if(!data.hasOwnProperty(i)) { continue; }
          
          listItems.push('<li id="listItem-'+ i +'">'+ data[i] +'</li>');
        }
      
        return listItems;
      })
      .then(function(items) {
        
        return $('<ul />', {
          html: items
        });
      })
      .then(function(list) {
        return $('#result').append(list);
      })
    ;
    
    
  };
  
  self.btn.click(self.loadData.bind(self));
}


jQuery(document).ready(DataCtrl);
#result { width: 100%; min-height: 10em; background: lightseagreen; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="btn">Load Data</button>
<div id="result"></div>

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

Validation of Single Fields in Angular Reactive Forms

When I validate a reactive form in Angular, I expect the error message to show up beneath the invalid field whenever incorrect data is entered. <form (ngSubmit)=sendQuery() [formGroup]="form"> <div *ngFor='let key of modelKeys&ap ...

Can anyone help me understand why I keep encountering errors when using a contain query to search for elements?

Could you kindly explain to me why I am encountering an error in the containment query? http://sqlfiddle.com/#!17/67b79/8 select * from Test where body @> '{"n","qwe"}::jsbonb'; Error ERROR: invalid input syntax for type json Detail: Exp ...

Getting information from a JSON file with several variables: A guide for using node.js, express, and jQuery

In order to minimize the number of Ajax calls, I am attempting to send three variables in a single Ajax response. However, I am facing difficulties when trying to process the data on the client side. Let me elaborate on my issue and if sending multiple var ...

Transferring a JSON object to a PHP script

I am attempting to send a JSON object with a structure like this: {"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]} Just to note: The sizeTypes array contains a total of approximately 58 items. Upon clicking the submit ...

What is the best way to send a populated custom class from JavaScript to a .NET MVC app using AJAX?

I am working with a .NET class in C# called BusinessModel: public class BusinessModel { public string BlobName { get; set; } public string NewName { get; set; } } In my MVC Ajax Controller, I have an action called DoBusiness: [HttpPost] public A ...

Guide on how to display registration form data on the current page as well as on a separate page

I am facing an issue with outputting registration form data to two different pages after successful validation. Specifically, I want the form data to be displayed on both the current page (form.php) and another page (profile.php). Despite my efforts to fin ...

Make sure to include the target blank attribute in your custom PHP code for

Is there a way to open a link in a new window? <?php if(get_option_tree('rss')) { ?> <a href="<?php get_option_tree('rss',$theme_options,'true'); ?>" id="rss" title="RSS" class="tt_top"></a><?php } ...

Update a div in PHP using the data received from an AJAX response

I recently developed a PHP application and encountered an issue with updating the value of a date picker. The user is prompted for confirmation when changing the date, and upon confirmation, the date in the "expiry" field (with id expiry) should update alo ...

What are all the functionalities provided by jquery select?

Currently, I am venturing into testing out a new jQuery plugin. let myPlugin = new MyPlugin(); $(#myPlugin).someFunction(); console.log($(myPlugin)) I'm curious - is there a way for me to see a full list of the available functions/methods for me to ...

What is the best way to transform a rectangular image into a square using CSS?

It's a common misconception that CSS can directly modify images, hence the quotation of "crop." My goal is to take rectangular images and apply CSS to give them a square appearance without altering the image itself. Essentially, I want to transform ...

Display popup just one time (magnific popup)

Attempting to display this popup only once during a user's visit. It seems like I might be overlooking something. <script src="http://code.jquery.com/jquery-1.7.min.js"> <link href="http://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1 ...

How to update the image URL using jQuery

Due to challenges with achieving a consistent background across various browsers, I have resorted to using a div with an image to cover the entire page. My goal is to have this image change based on the time of day. Previously, I had success using the tra ...

Steps for generating a BQ-schema from an XSD

Looking for assistance on a particular problem our integration team is facing. We are currently receiving xml files that are converted to json and sent to pub/sub. The challenge comes when ingesting these json files into bigquery, as the xml files do not a ...

Determining the Size and Color of Squares in a Treemap Based on Content with D3.js

I encountered an issue with a treemap visualization. I came across an example that is similar to my situation, which can be viewed here: In the demo, you can see that the size of each square in the treemap is determined by the content size. However, all s ...

Unable to retrieve a string from a JSON object

I have encountered an issue while using the gson library to retrieve JSON data from an HTTP request. Everything seems to be working correctly, with one exception - when I try to compare the received string, the string.equals method fails even for identical ...

Switch the class on the div that is currently being hovered over

Is there a way to apply a class toggle only to the currently hovered div? This is what I have so far: <script language="javascript" type="text/javascript"> $(document).ready(function () { $(".recipe-content").hover(function(){ $(".recipe ...

Typo3 Issue: Jquery Ajax Loading Homepage Issue

Here is the issue I am facing: I recently inserted the following code into a page within Typo3 (.../index.php?id=18). The content type of the element is pure html (special->html). <select name="testvariable" id="testvariable"> <option value ...

Reloading the webpage while simultaneously shutting down the modal popup with jQuery

My Issue : One of my challenges involves a modal form that appears when I click on a submit button. This form allows users to input information and request a demo from an organization. The data entered into the form is then stored in a MySQL database usin ...

Is there a way to conceal the parent element when the child element is hidden from view?

Wanting to remove the stars badge in the review section of a Shopify store when there are 0 reviews for the product. The goal is to have the badge appear automatically once a review is received. Here's the code snippet: HTML <div class="spr- ...

Mastering the art of curating the perfect image for your Facebook timeline

Controlling the Like image presented on Facebook timeline can be done using the header element. In my single-page app, I have multiple like buttons, each should be connected to a different image. What is the best way to associate a specific image with e ...