Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying json html data inside a div

I am trying to display some html from a json file into a div of my web site, but have only managed to get it displayed in the console. This is my code so far:

<div id="customSidebar" onload="sidebarContent()">
</div>

<style>
    #customSidebar {
        background-color: green;
        position: fixed;
        top: 120px;
        left: 100px;
        z-index: 100000;
        width: 300px;
        min-height: 300px;
        height: auto;
    }
</style>


<script>
    function sidebarContent(){
        fetch('*url*', {
            headers: {
                'Accept': 'application/json, text/plain, */*'
            }
        })  

        .then(response => {
            return response.json().then(data => {
                if (response.ok) {
                    return data.mainContent;
                } else {
                    return Promise.reject({status: response.status, data});
                }
            });
        })
        .then(result => console.log('success:', result))
        .catch(error => console.log('error:', error));
    }

    document.getElementById('customSidebar').innerHTML = sidebarContent();
</script>

Can anyone tell me what I am missing/have done wrong? Thanks!`

like image 709
Solveig Knutsen Avatar asked Mar 30 '26 01:03

Solveig Knutsen


1 Answers

Result of your function is promise, not string content. So you need to use resolved value for assignment:

function sidebarContent() {
    return fetch('*url*', {
        headers: {
            'Accept': 'application/json, text/plain, */*'
        }
    })
    .then(response => {
        return response.json().then(data => {
            if (response.ok) {
                return data.mainContent;
            } else {
                return Promise.reject({ status: response.status, data });
            }
        });
    });
}

sidebarContent().then(content => document.getElementById('customSidebar').innerHTML = content);
like image 59
udalmik Avatar answered Apr 02 '26 04:04

udalmik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!