Guide on incorporating data from JSON into a table with JavaScript

Following a tutorial from this source, I am working on creating a real-time table using PHP and AJAX. The PHP file sends back JSON-formatted values:

{ "retcode" : "0 Done", "trans_id" : "187472", "answer" : [ { "Country" : "US", "Digits" : "5", "Datetime" : "1586259875", "DatetimeMsc" : "1586259875596", "First" : "1.08580", "Second" : "1.08589" } , { "Country" : "China", "Digits" : "5", "Datetime" : "1586259877", "DatetimeMsc" : "1586259877000", "First" : "1.23311", "Second" : "1.23327"} , { "Country" : "Russia", "Digits" : "3", "Datetime" : "1586259874", "DatetimeMsc" : "1586259874585", "First" : "108.897", "Second" : "108.914" } ] }

The JS function I'm using to keep the values up-to-date in real-time is:

update : function (data) {
var message = "<p>Retcode: " + data['retcode'] + "</p>";
message += "<p>Trans ID: " + data['trans_id'] + "</p>";
message += "<p>UPDATED: " + data['answer'] + "</p>";
document.getElementById("values").innerHTML = message;
symbols.last = data['t'];
symbols.poll(); 
}

The PHP code snippet for fetching symbols continuously goes like this:

while (true) {
$symbols=$request->Get('/symbol_last?country=US,China,Russia');
if($symbols!=false)
{
$newsymbols=json_encode($symbols);
echo $newsymbols;
return $newsymbols;
break;
}
sleep(1);
}

This HTML file contains the necessary setup:

<!DOCTYPE html>
<html>
<head>
<title>AJAX Long Polling Values</title>
<script src="symbols.js"></script>
</head>
<body>
<div id="values"></div>
</body>
</html>

The output can be seen here:

https://i.sstatic.net/Cv8L0.png

How can I access and display other details from the 'answer' key such as Country, First, Second in a table format? Appreciate any help.

Answer №1

To successfully update, make sure to convert your string into a JSON object first.

update : function (data) {
    var jsonData = JSON.parse(data);
    var message = "<p>Status Code: " + jsonData['status_code'] + "</p>";
    message += "<p>Transaction ID: " + jsonData['transaction_id'] + "</p>";
    message += "<p>UPDATED: " + jsonData['response'] + "</p>";
    document.getElementById("values").innerHTML = message;
    symbols.last = data['t'];
    symbols.poll(); 
}

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 access a specific item within a Json object in a React component?

I am facing an issue where I receive a JSON object from my express backend in my react application, but I am unable to access the username property. I need to retrieve the value stored in the username field. After storing the JSON object in my react state ...

req.body returns as an empty object

I'm currently utilizing body-parser, but it seems to be malfunctioning without any clear indication of what the issue might be. app.js var createError = require('http-errors'); var express = require('express'); var path = require ...

I require assistance in configuring the timing for an animation using Jquery

How can I adjust the timing (delay between two words) for this animation? If you need help, you can check out this link for guidance. Feel free to share your suggestions! ...

Difficulty arises in AngularJS Material when attempting to access the same object value using ng-model and ng-change

I'm working with angular-material and facing an issue with an md-switch element. The model of the switch is determined by a value in a JavaScript object. However, I want to avoid directly changing the object value when the user toggles the switch. Ins ...

Guide on displaying only one v-menu when clicking to reveal the menu

I have implemented the v-for loop on v-menu and I am attempting to trigger the v-menu to open using only the button. My goal is to open one menu at a time when the button is clicked. Currently, all buttons are being displayed simultaneously because the v- ...

What are some ways to handle JavaScript exceptions effectively?

Within my application, I am retrieving the content from a different domain's page. This content includes specific JavaScript that is executed alongside the page. However, there is an issue with the following line of code within the JavaScript: "docume ...

Error message "invalid function call this.job.execute" when using Node.js node-schedule npm package

Having just started with nodejs, I created a nodejs program and set it to run every minute using the node-schedule library. However, after running for some time and producing several logs in the console, I encountered an error stating that this.job.execute ...

Trouble organizing a collection of destinations based on their geolocation and proximity

To address this issue, my approach has been to feed variables into the value attributes of an option list and then sort it based on these values. When manually assigning values, everything works smoothly, for example: <option id="link1" value="1">A& ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Numerous Capabilities of Javascript

I have a question about JavaScript and how to implement multiple functions on a webpage. I am new to JavaScript and struggling with getting multiple functions to work successfully. I have searched online but can't find a solution that fits my specific ...

Expanding a div container to accommodate its inner divs using CSS

I have a div containing three inner divs. ONE - I am div TWO - I am div THREE - I am div When viewed on mobile, only two divs can fit in a row horizontally. I want the third div to move down. Like this: ONE - I am div TWO - I am div THREE - ...

Adding a button input and deleting non-functional parent elements

Here is a simple append function using jQuery, and it's working perfectly. However, the issue arises when I try to append a button and remove the parent tr upon clicking. The problem lies in using remove parent, as it doesn't seem to work as exp ...

Where on the webpage does the scrolldown function in the webdriver look for information?

Check out this code snippet: var elem = driver.FindElement(ObjectName); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", elem); I'm curious - does the scroll down operation start searching for the element f ...

Bespoke HTML, CSS, JavaScript, and PHP website designs within the Wordpress platform

I am a beginner in the world of Wordpress, coming from a background of creating websites from scratch. Currently, I am working on a Wordpress template (Astra) and looking to create a custom page using HTML, CSS, JavaScript, and PHP from the ground up to ad ...

The problem arises when Angular's $interval function is not recognized

Despite the possibility of this being considered a duplicate, none of the related topics have provided a solution to my simple date count down directive: class Clock { constructor() { this.restrict = 'AC'; this.replace = true ...

What is the process for building a morph animation using sliders in three.js?

I recently completed a morph animation in Blender, where I created a transformation from a slim avatar to a fat avatar using shape keys. Now, I am attempting to export this animation to three.js and implement a slider that allows users to change the avat ...

Maintaining Flexbox layout without triggering item re-rendering for a new container

This is the unique layout I'm aiming to create: I am facing a challenging flexbox layout that needs to be implemented. One of the items in this layout is a Webgl player, which cannot be conditionally rendered due to the restarting issue it may cause. ...

Unable to redirect to Jade page in Node.js

I recently delved into the world of node js a few days ago. When I click on a button, a function with an ajax call is triggered. function goToUser(){ $.ajax({ url:"/users/UserPage", type:'get', async:false, su ...

When attempting to search and parse input text using a code replication technique, a console error is generated

Trying to extract the answer from this question's comment. The current code is displayed below, but struggling with removing the Dealing with an Unexpected token } error in Chrome console. Any ideas on how to fix this? Also looking for a Chrome pl ...

The Next.js middleware, specifically NextRequest.nextUrl.locale, will return an empty string once it is deployed

Encountering a bug in the next-js middleware The middleware function is returning a NextRequest param According to the documentation from Next.js: The NextRequest object is an extension of the native Request interface, with the following added metho ...