Using Fetch command to store JSON data into HTML variable

I finally surrendered and started using JSON. And I used the Javascript Fetch command for the first time. It works very well if you want to display JSON data inside the console.log. But if you want to display the data inside a HTML textbox, beware. You either get undefined data or Object Object. I know that there is some kind of async await command combination. But that creates a new problem. I get an error stating something about esversion 8. I tried to look up this information but I guess no one works with super easy web projects. So that was no help. Here is my current code:

JSON_Example.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First JSON Experiment</title>
<link rel="stylesheet" type="text/css" href="http://localhost:8080/exist/rest/db/apps/HTML_Student/JSON_Example.css"/>
<script language="javascript" src="http://localhost:8080/exist/rest/db/apps/HTML_Student/JSON_Example.js"/>
</head>
<body onload = "Setup()">
<input type = "text" id = "JSON_Text">
</input>
</body>
</html>

JSON_)Example.css

#JSON_Text {
    position: absolute;
    top: 200px;
    left: 300px;
    height: 25px;
    width: 300px;
}

JSON_Example.js

function Setup() {
    var XMLHttp;
    var JSON_Data;
    var JSON_Output;
    var URL;
    
    
 URL = 'http://localhost:8080/exist/rest/db/apps/HTML_Student/people.json';

     fetch(URL)
          .then(res => res.json())
          .then(data =>  {JSON_Data = data})
          .then(() => {console.log(JSON_Data);
          document.getElementById("JSON_Text").value = JSON_Data;
          
   });
         
          
     
    
}    
  

People.json

{"name":"John", "age":30, "city":"New York"}
1 Like

What do you expect the input field to contain if you give him an object as value? This cannot work. The value of an input field must be a string.

Hi @megelinic , if you just want to get the response text as a string, use then(res => res.text()) instead (or JSON.stringify() the data where needed as a string).

(x-post)

This solved one half of my problem. res.text() definitely works and I did see the text from my JSON document. However, what I really need to see is John, 30, and New York without all the other parameters. How would I do that?

When you use the res.json() you get an object which contains all attributes of your json file.
So you can format your output value as whatever you want. E.g.

try
{
    response = await fetch(url);
    myObject = await response.json();
    document.getElementById("JSON_Text").value = myObject.name + " - " +  myObject.age;
}
catch(error)
{
    console.log(error);
}

You should use the more modern and much more readable await Syntax instead of the old then() one.

Also you should keep the case conventions used by all developers. Variables are named in camelCase.

I really appreciate all of your assistance. There are a few complications that you may not be aware of. I wanted to let you know that Iā€™m an over 50 year old computer programmer. In my heyday I programmed an NCR mainframe using ancient COBOL. Sometimes I yearn for those days.

There are two ways that my javascript code can work. And I wanted to share both of these codes so that others may benefit from my work. Here is code #1:

function Setup() {
    var XMLHttp;
    var JSON_Data;
    var JSON_Eement;
    var Retrieved_Data;
    
    
    
    XMLHttp = new XMLHttpRequest();
          XMLHttp.open("GET","http://localhost:8080/exist/rest/db/apps/HTML_Student/people.json", true);
          XMLHttp.onreadystatechange = function () {
            if (XMLHttp.readyState == 4) {
              JSON_Data = XMLHttp.responseText;
              JSON_Element = JSON.parse(JSON_Data);
              document.getElementById("JSON_Text").value = JSON_Element.name + "Here."}
              
          };
          XMLHttp.send();}

And here is code #2:

function Setup() {
    var XMLHttp;
    var JSON_Data;
    var JSON_Output;
    var URL;
    
    
 URL = 'http://localhost:8080/exist/rest/db/apps/HTML_Student/people.json';

     fetch(URL)
          .then(res => {return res.text()})
          .then(data =>  {JSON_Data = data})
          .then(() => {console.log(JSON_Data);
          let JSON_Output = JSON.parse(JSON_Data);
          document.getElementById("JSON_Text").value = JSON_Output.name;
          
   });

The only problem is with the await function. If I use the latest version of the eXist Database, I get the following error: ES8 needs to be used. Iā€™m not sure if there is something not working properly in eXist, but thatā€™s the error I get. Is there some way to get around this error?

I donā€™t think you have to parse the data?

Hereā€™s a high scores table I did awhile back ā†’

    /* retrieve User Data from hs_table */
    const retrieveHSTableUISuccess = function (info) {
        displayHSTable(info);

    };

    /* If Database Table fails to save data in mysql table */
    const retrieveHSTableUIError = function (error) {
        console.log("Database Table did not load", error);
    };
    const output_high_scores_to_screen = (url, onSuccess, onError) => {
        const maxRecords = 0;
        const data = { max_limit: maxRecords };

        fetch(url, {
            method: 'POST',
            body: JSON.stringify(data)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Network response was not ok. Status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => onSuccess(data))
            .catch(error => onError(error));
    };

    output_high_scores_to_screen(
        'read_high_scores.php',
        retrieveHSTableUISuccess,
        retrieveHSTableUIError
    );

Iā€™d say:

function Setup() {
    const URL = 'http://localhost:8080/exist/rest/db/apps/HTML_Student/people.json';

    fetch(URL)
        .then(res => { return res.data() })
        .then(data => { document.getElementById("JSON_Text").value = data.name });
});

Hey, awesome that youā€™re jumping into JSON and using the fetch command! I know it can be a bit frustrating when things donā€™t work as expected, especially when youā€™re trying to display the data in an HTML textbox.

The issue youā€™re running into happens because youā€™re trying to stick an entire JSON object into a textbox, and JavaScript doesnā€™t quite know how to handle thatā€”it ends up just showing [object Object], which isnā€™t very helpful.

Hereā€™s a quick fix:

Instead of trying to put the whole JSON object into the textbox, youā€™ll want to either display a specific piece of the data (like just the name, age, or city) or convert the whole JSON object into a string that can be displayed.

Hereā€™s how you can update your Setup function:

function Setup() {
    var URL = 'http://localhost:8080/exist/rest/db/apps/HTML_Student/people.json';

    fetch(URL)
        .then(res => res.json())
        .then(data => {
            console.log(data);  // This shows the JSON object in the console

            // To display just the name in the textbox
            document.getElementById("JSON_Text").value = data.name;

            // Or, if you want to show the whole JSON object as a string:
            // document.getElementById("JSON_Text").value = JSON.stringify(data);
        });
}

Whatā€™s Happening:

Displaying Specific Data: If you just want to show, say, the name from your JSON, you can access it directly with data.name.
Converting to a String: If you want the whole JSON object to show up in the textbox, you can use JSON.stringify(data) to convert the object into a string format that can be displayed.

About the async/await and esversion 8 error you mentionedā€”itā€™s just a different way of handling the asynchronous code (like fetch), but if youā€™re getting errors, itā€™s probably because your environment isnā€™t set up to support it yet. Sticking with the .then() method youā€™re using is totally fine!

Give this a try, and it should fix the issue. If you run into any more problems or have questions, just let me know. Youā€™re doing greatā€”keep at it!

I wanted to thank everyone for their assistance. Itā€™s nice to know that someone like me who is over 50 years old can still get this kind of assistance. After nearly a day of experimentation, I finally realized what everyone was saying about retrieving data from JSON. So I corrected my code and now it looks like this:

`function Setup() {
    var XMLHttp;
    var JSON_Data;
    var JSON_Output;
    var URL;
    
    
 URL = 'http://localhost:8080/exist/rest/db/apps/HTML_Student/people.json';

     fetch(URL)
          .then(res => {return res.text()})
          .then(data =>  {JSON_Data = data})
          .then(() => {console.log(JSON_Data);
          let JSON_Output = JSON.parse(JSON_Data);
          document.getElementById("JSON_Text").value = JSON_Output.name;
          
   });
   
}    `

A lot of people want me to use the await command, but Iā€™m using the eXist database and I keep receiving an error message about something called es8. Since I donā€™t know about es8, I canā€™t fix the error. I could use some help with this.

In my next project Iā€™m struggling with SVG and the positioning of input buttons and textboxes. Iā€™m assuming that using the div tag will fix this bug. If it doesnā€™t work, I will let you know.

That code is incorrect, as itā€™s mixing asynchronous code with synchronous code. It might accidentally work if the network is fast, but when network is slower itā€™ll throw errors. Did you look at my previous post?

Also, you donā€™t necessarily need await if you use .then instead, which you are, sorta.

1 Like

@megelinic,

The .then sets up a function to run later, and by later I mean after your main code has executed. You can think of it a bit like an eventListener

document.addEventListener('click', (e) => console.log('logged later when you click'))
console.log('logged first')

Both the eventListener and the .then take a function. In the case of the addEventListener it waits for a click on the document to trigger that function. In the case of your .then it is going to wait until some data has been fetched successfully to trigger itā€™s function.

As rpkamp has pointed out, that would depend on the speed of your network.

Either way the code under your .then chain is going to execute before the .then functions.

Here is an example

function main() {
  const URL = 'https://jsonplaceholder.typicode.com/users/1';

  fetch(URL)
    .then(response => response.json())
    .then(user => {
      console.log('I got here some time later')
      document.querySelector('#json-text').textContent = user.name
    })
  console.log('I got here first!!!')
}

main()

If you look at the console you see this is what is logged

"I got here first!!!"
"I got here some time later"

This might be helpful

I do want to apologize to RPKAMP. I didnā€™t receive your initial message until Tuesday. Thatā€™s because I spent all day trying to make this code work. I was so exhausted that I finally fell asleep at my computer. But my last attempt finally worked.

As you probably noticed, I was executing my code on the eXist database that is installed and running on my computer. So speed was no issue.

I will make the necessary code corrections that you recommended as I build my next project. But as a former COBOL and Visual BASIC programmer, I was taught to group my variables together and place them at the beginning of my function. Thatā€™s why I never use the const feature. I doubt that will affect the performance of any function that I will create from this time forward.

That was a standard in JS too going back a decade or so ago. I would presume that was in part due to JS programmers having backgrounds in classic programming languages. It was also inline with how JS functions hoist variables to the top anyway.

Here are a couple links for const and let that I hope are helpful.

To RPKAMP. I copied and pasted your code. Then I opened my HTML page. Nothing appeared in the textbox. So it appears there is something wrong with your code. And my eXist database called an unnecessary parenthesis on the final parenthesis. So Iā€™m not sure what went wrong. I did receive an error in the console. Here was the error:

SVG_Diagonal_Line.js:18 Uncaught (in promise) TypeError: res.data is not a function
at SVG_Diagonal_Line.js:18:35

I stored a JSON array in another file. Then I tried to access the data in that file. I was unable to access this data. Iā€™m not sure why I was unable to access it. I could use a little assistance.

Ah, res.data() should have been res.json()

I really appreciate the update that RPKAMP gave to me. Your code now works perfectly. Iā€™m trying to create a JSON array to accommodate my next project. So I decided to make a couple of adjustments on this code to learn how to properly construct an array.

So I borrowed some code from a webpage and decided to place it into a JSON document. Here is the code I borrowed:

'{"model":[' +
    '{"carName":"Baleno","brandName":"Maruti" },' +
    '{"carName":"Aura","brandName":"Hyndai" },' +
    '{"carName":"Nexon","brandName":"Tata" }]}';

Then I made a couple of adjustments to my Javascript code:

function Setup() {
    var URL = 'http://localhost:8080/exist/rest/db/apps/HTML_Student/SVG_JSON_Test.json';

    fetch(URL)
        .then(res => res.json())
        .then(data => {
            // To display just the name in the textbox
            document.getElementById("Data_Text").value = data.model[2].carName;

            // Or, if you want to show the whole JSON object as a string:
            // document.getElementById("JSON_Text").value = JSON.stringify(data);
        });
}

Of course once again nothing displays in my textbox. I checked the console and I got this error: VM924:1 Uncaught (in promise) SyntaxError: Unexpected token ā€˜ā€™ā€˜, "ā€™{ā€œmodelā€:"ā€¦ is not valid JSON What am I doing wrong?

I examined another website and fixed my JSON code:

{"model":[
	{"carName":"Baleno","brandName":"Maruti" },
    {"carName":"Aura","brandName":"Hyndai" },
    {"carName":"Nexon","brandName":"Tata" }]}

When I ran my webpage again, the console error disappeared and I got the result of Nexon. But when I tried to change the model, the name Nexon kept appearing in the textbos. Iā€™m not sure why it didnā€™t change to another model.

I stand corrected. The ctrl F5 feature once again wasnā€™t responding. So I took the next bold step and created a new JSON document. Here is what I created:

{"Diagonal_Line_1": [
          {"First_X1_Coordinate": "200px",
           "Second_X1_Coordinate": "295px",
           "First_Y1_Coordinate": "200px",
           "Second_Y1_Coordinate": "300px"}]}
{"Diagonal_Line_2": [           
           {"First_X1_Coordinate": "400px",
           "Second_X1_Coordinate": "305px",
           "First_Y1_Coordinate": "200px",
           "Second_Y1_Coordinate": "300px"}]}

Now the eXist program says there is a syntax error when I begin Diagonal_Line_2. I donā€™t know what Iā€™ve done wrong.

I admit that Iā€™m very new at this. I added a category to solve the syntax problem. Now my code looks like this:

{"Diagonal_Lines": [
     {"Diagonal_Line_1": [
          {"First_X1_Coordinate": "200px",
           "Second_X1_Coordinate": "295px",
           "First_Y1_Coordinate": "200px",
           "Second_Y1_Coordinate": "300px"}]},
     {"Diagonal_Line_2": [           
           {"First_X1_Coordinate": "400px",
           "Second_X1_Coordinate": "305px",
           "First_Y1_Coordinate": "200px",
           "Second_Y1_Coordinate": "300px"}]}
          
]}

So letā€™s say I want to access Diagonal_Lines and then access Diagonal_Line_1 and then access First_X1_Coordinate. How would I display that in my textbox?