Exploring JS Object Property Access and Iteration with an Illustrative Example

Something strange is happening... the code snippet below generates a table displaying a list of SNMP object/values from any OID provided for walking. Strangely, the variable 'jason' is not behaving as expected.

Initially, I am unable to access the 'jason' object from the Chrome console using console.log or console.dir.

Furthermore, when a console.log(key) is placed within the 'for in' loop, nothing is outputted.

Moreover, when attempting to access the properties of 'jason' using dot notation within the for loop, 'undefined' is returned.

Lastly, despite reading on other Stack posts that an array-like object should not utilize the 'for in' loop, changing it to a regular for loop causes it to malfunction. It seems like the 'jason' variable is invisible, even though the script below functions correctly. Could it be a fundamental misunderstanding of the JavaScript language on my part? Any insights would be greatly appreciated.

document.getElementById('submit').addEventListener('click', function(){

document.getElementById('msg').innerHTML = '<br /><button class="btn btn-success" disabled="disabled"> <i class="fa fa-spinner fa-spin"></i> </button> Loading...';
request = new XMLHttpRequest();
var host = document.getElementById('host').value,
    comm = document.getElementById('comm').value || 'public',
    oid = document.getElementById('oid').value || '1.3.6.1.2.1.2.2';
var post_vars = 'host=' + encodeURIComponent(host);
post_vars += '&comm=' + encodeURIComponent(comm);
post_vars += '&oid=' + encodeURIComponent(oid);
request.open('POST', 'snmp_json.php');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.addEventListener('readystatechange', function() {
  if (request.readyState === 4 && request.status === 200) {
    var jason = JSON.parse(request.responseText);
    var output = '<table class="table table-hover">';
    output += '<thead><tr><th>Object</th><th>Value</th></tr></thead>';
    output += '<tbody>';
    for (key in jason) {
        output += '<tr><td>' + key + '</td>';
        output += '<td>' + jason[key] + '</td></tr>';
    }
    output += '</tbody></table>';
    document.getElementById('msg').innerHTML = output;
  };
});
request.send(post_vars);

});

Answer №1

Chrome is unable to access the JSON object due to its private nature within the event handler. To successfully retrieve the object, it is recommended to declare JSON outside of the event handler, preferably before

document.getElementById('submit')

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

A guide on installing a npm dependency module from a local registry domain

I have successfully published a module on my own custom registry domain, located at , and I am able to publish updates to the module there. Unfortunately, I am encountering an issue with dependencies within my published module. For example: "dependencies" ...

Encountering a situation where an empty value is being received from an

After submitting the form, I am receiving null values via ajax. Currently, I have 3 fields in the form and I am unable to retrieve any values from it. Please assist me in finding a solution. <table class="table table-hover table-centered m-0 table-bo ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

Changing marker colors dynamically in Google Maps with NextJS

I'm using the @googlemaps/js-api-loader package to load a map in my nextJS app. I have a list of locations that I want to plot on the map, and I also want these locations disabled on the left side of the page. When hovering over one of the locations ...

JavaScript dropdown menu that dynamically changes colors

<!DOCTYPE html> <html> <head> </head> <body> <script> var redtoggle=false; function togglered() { redtoggle = !redtoggle; if (redtoggle) { document.getElementById("txtInput").style.color = "red"; } else { do ...

Unforeseen behavior in the definition of requirejs

This first snippet of code is functional: define([ 'jquery', 'underscore', 'backbone' ], function($, _, Backbone,home_template) { var HomeView = Backbone.View.extend({ render: function() { ...

Using Angular JS services and controllers in separate files may result in errors

Within my angularjs project, I manage the following files: /index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-wid ...

Observing changes in a parent component variable with Angular

One feature of my form is that it consists of a parent component and a child component. To disable a button within the form, I utilize a function called isDatasetFilesValid() which checks a specific variable (datasetList[i].fileValid). This variable is mo ...

What is the process of embedding a Vue.js application into an already existing webpage using script tags?

My goal is to integrate a Vue.js application into an existing webpage using script tags. Upon running `npm run build` in my Vue application, I end up with 7 compiled files: app.js app.js.map manifest.js manifest.js.map vendor.js vendor.js.map app.css In ...

Ways to remove items from Vuex store by utilizing a dynamic path as payload for a mutation

I am looking to implement a mutation in Vuex that dynamically updates the state by specifying a path to the object from which I want to remove an element, along with the key of the element. Triggering the action deleteOption(path, key) { this.$store.d ...

Transform a checkbox input into two distinct buttons

I am trying to change the input checkbox that toggles between light and dark mode into two separate buttons. How can I achieve this functionality? Check out the demo here: https://jsfiddle.net/ot1ecnxz/1 Here is the HTML code: <input type="checkb ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

Dealing with cross-origin error issues when using json.parse in React / MERN development

My data structure functions correctly when I use console.log: console.log(JSON.parse([values.category2]).needed_skills); However, when I pass the output of JSON.parse([values.category2]).needed_skills to a component in my application, the entire system c ...

For optimal display on mobile devices, include "width=device-width" in the meta tag "viewport"

Is it necessary to include "width=device-width" in the meta tag named viewport when dealing with mobile phones? I've been attempting to make use of this, but without success: //iPhone Fix jQuery(document).ready(function(){ if (jQuery(window).widt ...

Using the power of HTML5, store data locally on

I am curious about the possibility of using local storage on a different page. I want to track clicks made on one page and display it on another, but I'm not sure how to go about it or if it's even feasible. Any help you can provide would be grea ...

Understanding and aggregating data from JSON files

I am in possession of a group of json values outlined below {"labels":[ "time", "softirq", "user", "system", "nice", "iowait" ], "data":[ [ 1490088352, 0, 14.64646, 3.53535, 0, 1.0101 ], [ 1490088351, 0, 27.77778, 3.0303, 0, 0 ], [ 1490088350, 0.49751, 12 ...

An issue has occurred in the node-telegram-bot-api module: Unable to locate 'fs', 'net', 'tls' in node-telegram-bot-api

<pre> import React, { Component } from "react"; import { render } from "react-dom"; import Home from "./components/Home.jsx"; const TelegramBot = require('node-telegram-bot-api'); const token = "MY_TOKEN"; const bot = new TelegramBot(token ...

Adding style using CSS to a dynamically generated table row in Vue.js

Currently, I am working with a table that dynamically generates rows using v-for: <table> <tr><th class='name'>Name</th><th>Surname</th></tr> <tr v-for='data in datas'><td class=&a ...

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

initiating a submission upon the occurrence of an onchange event on an input field of type "file"

I have encountered an issue while trying to submit a form using the onchange event of an input element with type file. The problem is that it submits an empty form even when a file has been chosen. Here is the code snippet: var form = document.createElem ...