Converting JSON into HTML has me completely baffled

Despite my best efforts, I have managed to navigate my way through the code thus far, but I am puzzled as to why the JSON data is not being sent to the HTML via JavaScript. I can manually input the necessary parts in the developer console after onLoad and it works fine... However, when running the script on its own to automatically populate the empty divs on the page - nothing happens... I understand that it's likely a small oversight on my part, but I'm ready to move on from this frustrating aspect of the site. Any assistance would be greatly appreciated.

/* General Info                          */
/* Data Routing Structure:               */
/* (JSON DATA)   (jsVariable)  (cssID)   */
/* title         rTitle        rTitle     */
/* quote         rQuote        rQuote     */
/* source        rSource       rSource    */
/* text          rText         rText      */
/*---------------------------------------*/
/* All JSON Data Files Are Located In    */
/* (Root)/dta, And Are Split Into 12     */
/* Files.

/* Define Global Variables To Help       */
/* Specify The Current Day And Month     */
var date = new Date();
var m = date.getMonth();
var d = date.getDate();  
var months = new Array()
    months[0] = "january";
    months[1] = "february";
    months[2] = "march";
    months[3] = "april";
    months[4] = "may";
    months[5] = "june";
    months[6] = "july";
    months[7] = "august";
    months[8] = "september";
    months[9] = "october";
    months[10] = "november";
    months[11] = "december";
var month = months[date.getMonth()];


/* Make The Connection To The JSON File  */
    var drOb;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', "./dta/" + month +".json");
    xhr.overrideMimeType("application/json");
    xhr.setRequestHeader("Content-type", "application/json", true);

/* Pull JSON Data For Todays Date        */
/* When The Page Loads, And Send To HTML */
    xhr.onload = function() 
    {
      if (this.readyState == 4 && this.status == 200)
      {
        var drOb = JSON.parse(this.response);
        var rDate = m + d;
        var rTitle = drOb[DAY][d].TITLE;
        var rQuote = drOb[DAY][d].QUOTE;
        var rSource = drOb[DAY][d].SOURCE;
        var rText = drOb[DAY][d].TEXT;
        document.getElementById("rDate").innerHTML = rDate;
        document.getElementById("rTitle").innerHTML = xhr[DAY][D].TITLE;
        document.getElementById("rQuote").innerHTML = rQuote;
        document.getElementById("rSource").innerHTML = rSource;
        document.getElementById("rText").innerHTML = rText;

      }else{
        alert("Daily Reflection is currently not available, please inform someone....");    
      }
    };

    xhr.send();

Answer №1

XMLHttpRequest.onload

I believe it should be written as onload rather than onLoad.

Answer №2

Make sure to reference the documentation for XMLHttpRequests.

There are several issues that need addressing:

  • The event to monitor is either onreadystatechange or onload (ensure lowercase)
  • this does not refer to what you think it does. Use xhr instead. As @Marisha pointed out, unless you are using an arrow function, this actually gets rebound.
  • this.response should be replaced with xhr.responseText
  • xhr[DAY][D].TITLE should likely be changed to drOb[DAY][D].TITLE
  • Some variables (like DAY) used in your code are not defined.

Here is the corrected code. I have left certain sections blank for you to complete where my understanding was limited.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com');

xhr.onreadystatechange = function() {
  // This function will be executed multiple times.
  // If the status is anything other than 4 (complete), we should stop.
  if (xhr.readyState !== 4) return;

  if (xhr.status !== 200) {
    // Notify the user of an error and halt further execution.

    return;
  }

  // If this point is reached without returning, the request was successful.

  var drOb = JSON.parse(xhr.responseText);
  // Alternatively, consider using `var drOb = xhr.response`
  // depending on the server setup.
};

xhr.send();

Note: concerning this.response vs this.responseText, I recommended this change because this.response depends on xhr.responseType to determine how the response should be parsed, which may not be supported by all browsers (like IE). By utilizing this.responseText, you can ensure it is a string, and when combined with JSON.parse, you ensure proper parsing as JSON and enable try-catch functionality.

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

How to convert nested []interface{} into []map[string]interface{}

In my quest to transform a JSON into a structure of map[string]interface, I aim to convert all nested []interface{} into []map[string]interface{}. This conversion is necessary because we are utilizing the package https://github.com/ivahaev/go-xlsx-template ...

Navigate through JSON data to uncover the tree structure path

In my project, I am working on creating a treeview user interface using the JSON provided below. I have included properties such as node-id and parentId to keep track of the current expanded structure. Next, I am considering adding a breadcrumb UI compone ...

Tactics for postponing a js function post-click

I need to implement a delay after clicking a button to fetch some data. The code will be executed within the browser console. $(pages()) is used to retrieve the pagination buttons. let calls = []; for (let i = 1; i <= callPagesCount; i++) { ...

Asserting types for promises with more than one possible return value

Struggling with type assertions when dealing with multiple promise return types? Check out this simplified code snippet: interface SimpleResponseType { key1: string }; interface SimpleResponseType2 { property1: string property2: number }; inter ...

Utilizing jQuery Datatable for server-side processing to effectively generate and detect validation and various other errors

Currently implementing serverside processing with JQuery Datatables. Wondering the best way to intentionally create an error on PHP serverside and how to effectively catch and display it to the user. ...

I keep receiving an error in Angular JS but I'm unsure of the reason

I've been working on AngularJS and created a basic module and controller. I'm attempting to show the data of an element inside the controller on the HTML view page, but all I see is {{student.name}} and I'm receiving an error message that sa ...

How to Use jQuery in Thymeleaf to Toggle All Checkboxes

Why isn't the function of selecting and deselecting all fields working correctly for me? Can anyone explain what may be causing this issue? ..... <head> <meta name="viewport" content="width=device-width, initial-scale=1.0&q ...

Using Javascript to extract formatted text from a webpage and save it to the clipboard

I've developed a straightforward tool for employees to customize their company email signature. The tool generates text with specific styling, including bold fonts and a touch of color - nothing too extravagant. When I manually copy and paste the styl ...

Tips for extracting a website's dynamic HTML content after AJAX modifications using Perl and Selenium

When dealing with websites that utilize Ajax or javascript to display data, I'm facing a challenge in saving this data using WWW::Selenium. Although my code successfully navigates through the webpage and interacts with the elements, I've encounte ...

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

Retrieving particular data from a JSON file

I have decided to challenge myself by creating a Ruby file that prompts the user for a city input and then fetches weather data for that city using an API. Despite being new to Ruby programming and APIs, I am determined to make this work. Displayed below ...

Aligning container divs at the center in various screen resolutions

I recently constructed a portfolio website using Bootstrap and Isotope JS. In my layout, I have a container div which works perfectly when viewed on a desktop browser - displaying 3 divs in one line. However, the issue arises when the resolution changes an ...

Extract an image from a JSON payload

Currently, I am developing a discord.js bot that interacts with the last.fm API. I'm facing an issue where the image returned in the API response comes in different sizes and I want my bot to display it in a specific size within an embed message. Any ...

How to structure dates in JSON using PHP

I am looking to reformat the date and time into a more user-friendly format, such as '23rd September 2018 17.00' //JSON Array instances": [ { "start": "2017-08-02T14:15:00" } ] //PHP CODE $count = count($characters->instances); for(reset($i ...

Interact with multiple databases using the singleton design pattern in a Node.js environment

I need to establish a connection with different databases, specifically MongoDB, based on the configuration set in Redis. This involves reading the Redis database first and then connecting to MongoDB while ensuring that the connection is singleton. Here i ...

Unlocking hidden gridview column values with the power of jQuery

Within my gridview control, there are 4 columns, with one column being invisible which contains the Email Address information. <asp:GridView id='gridData' runat='server'> <Columns> <asp:TemplateField> ...

Utilizing Django to Showcase Images within DataTables and ListView

I am trying to incorporate a thumbnail image in a jQuery DataTables. A thread on Stack Overflow 1 suggests adding a js render function to the .DataTable settings. I want to implement this solution in a standard way, using Django's class-based ListVi ...

When using the JavaScript .sort() method, any undefined value must always be considered as coming before any other value

I am working on sorting an array of objects based on multiple fields, typically around 3-4 fields. Some values within the objects may be undefined, and I need to ensure that these undefined values are considered as "earlier" in the sorting process, wheth ...

Master the art of transforming Json data into a structured associative array

I am facing an issue with handling JSON data that was posted from a form and unable to process it or store it in a database. This is what the posted data looks like: Array ( [apd0] => [{"ratio":"1","size":"S","quantity":"83"},{"ratio":"2","size":"M ...

HTML experiences confusion as JSON tosses undefined data

Can someone assist me with API integration? I am new to this and trying to display the Poster, Title, and Year from an API URL. Here is the code I have been working on. When I log in, it shows JSON in an array but throws "undefined" in front-end. Your help ...