How to iterate over cfreturn serializeJson within a script tag in coldfusion

95 Views Asked by At

I am new to Coldfusion and trying to learn and develop an application.

I have a cfcomponent, which takes a start and end date and execute a query. The result of the query I serialize using the following

 <cfreturn serializeJSON(data=myloaddata,queryformat="struct") >

This works and the data is in this format.

[{"UTCTIME":"December, 15 2023 00:00:00","LOCALTIME":"December, 14 2023 19:00:00","UNIT_ID":1001,"LOAD_INT":null,"LOAD_INTTLQ":null,"Sample":2811,"SampleVal":2740},{"UTCTIME":"December, 22 2023 00:00:00","LOCALTIME":"December, 21 2023 19:00:00","UNIT_ID":1001,"LOAD_INT":null,"LOAD_INTTLQ":null,"Sample":2811,"SampleVal":2832}]

The issue I am facing is result is return to my $.get() call within my script tag.

<script>
$.get(`getMonthlyLoad.cfc?method=user.cfc&startDate=${range.start}&endDate=${range.end}`, function(data){
            console.log(data);
         });
 </script>

I would like to iterate over the result value in data to create html table, however when I iterate over data object it prints one character at a time. data[0] will show '[', data[1] will show '{' .. etc Basically printing character by character.

I don't understand why its not printing as an object since the result from the query is a json object. Any help would be great.

1

There are 1 best solutions below

7
snackboy On BEST ANSWER

Since the data on CF side is being serialized into a string, you would need to turn it back into an object on the JS side. In your JS code, try the following:

<script>
    $.get(`getMonthlyLoad.cfc? method=user.cfc&startDate=${range.start}&endDate=${range.end}`, 
    function(data){
        var myData = JSON.parse(data)
        console.log(myData);
    });
</script>

I was able to take the data you posted to make sure the output was good:

<script>
        function doStuff() {
            var _d = '[{"UTCTIME":"December, 15 2023 00:00:00","LOCALTIME":"December, 14 2023 19:00:00","UNIT_ID":1001,"LOAD_INT":null,"LOAD_INTTLQ":null,"Sample":2811,"SampleVal":2740},{"UTCTIME":"December, 22 2023 00:00:00","LOCALTIME":"December, 21 2023 19:00:00","UNIT_ID":1001,"LOAD_INT":null,"LOAD_INTTLQ":null,"Sample":2811,"SampleVal":2832}]';
            var _md = JSON.parse(_d);
            console.log('json',_md);
        }
    
        doStuff();
</script>

Output was as expected:

[
    {
        "UTCTIME": "December, 15 2023 00:00:00",
        "LOCALTIME": "December, 14 2023 19:00:00",
        "UNIT_ID": 1001,
        "LOAD_INT": null,
        "LOAD_INTTLQ": null,
        "Sample": 2811,
        "SampleVal": 2740
    },
    {
        "UTCTIME": "December, 22 2023 00:00:00",
        "LOCALTIME": "December, 21 2023 19:00:00",
        "UNIT_ID": 1001,
        "LOAD_INT": null,
        "LOAD_INTTLQ": null,
        "Sample": 2811,
        "SampleVal": 2832
    }
]