Search code examples
javascripthtmlgoogle-visualizationgetjson

Rendering a JSON value in a google table cell


I've got a google table that gets populated but one column needs to get live data from an API using the row's url value.

Using a function like this would get me the value:

$(function(){
    getPrice('www.example.com/specificJSON')
    function getPrice(url) {
        $.getJSON(url, function (data) {
            console.log(parseInt(data.value));
            return data.value
        })
    }
})

But how can I link this to the table? Imagine every row has its own url that dynamically needs to get the value and print in the table cell. Is there a way to call my function from the cell with the url as variable? I can print anything in the cell as a string.

Hypothetically the string could be something like:

'getPrice('www.example.com/specificJSON2')'

When loaded would become:

24

Another approach would be to cycle through the rows when the table finished loading and start replacing the cell's information I guess? What would be best to do here, keeping in mind that it should be somewhat quick.

Ideally I would like to do the same as getting an image from a source (<img src="www.thebestimage.com">), but then a jsonvalue.

EDIT: So contrary to many posts about using JSON with Tables I am not generating the table from JSON data but rather need to dynamically display jsondata in a single cell. The information of the retrieval is rendered in the table already.


Solution

  • I solved it by using the following HTML in the cell:

    '<span class="getValue" data-Id="24">Loading...</span>'
    

    This can be generated beforehand as a string.

    Then with this event listener I can load the data:

    google.visualization.events.addListener(table, 'ready', function(){
        $('.getValue').each(function(){
            var self = $(this)
            var id = this.getAttribute('data-Id')
            $.getJSON('www.getjsondatawithid/'+id, function (data) {
                try {
                    self.text(data.text.first) //Select the JSON value.
                } catch(err) {
                    self.text('Error') //Or set the text to error.
                }
            })
        })
    })
    

    This will replace the span text of each cell. Be sure to enable HTML in the google table draw options:

    table.draw(data, {showRowNumber: true, width: '100%', height: '100%', allowHtml: true});