How can I cfoutput a JavaScript String?

752 views Asked by At

I'm building a JSON string within script Tags in a cfm file. I would like to find a way to get this JSON string into a cfoutput so that the page can display the JSON.

I'm currently just document.write()ing the json which retrieves the JSON in the browser but won't return anything with a POST request. I've tried using the toScript() coldfusion function but I think this does the opposite of what I want (puts cf var into js when I want to put a js var into cf).

I'm currently doing this

<cfoutput>
    <script type = "text/javascript"> 
        var someJSON = "{\"some\": \"data\"}";
        document.write(JSON.stringify(someJSON));
    </script>
</cfoutput>

I'm still getting to grips with coldfusion so sorry if this seems archaic. I would like to instead pass someJSON to a coldfusion variable so I can cfoutput tag so that I get a response with a POST request to this particular endpoint because currently I get no response.

2

There are 2 answers

1
James A Mohler On

To get a string out ColdFusion and into Javascript, you need to do something like this:

<cfset cfdata = {"some": "data"}>


<cfoutput>
<script type = "text/javascript"> 
    var someJSON = #serializeJSON(cfdata)#;
    document.write(JSON.stringify(someJSON));
</script>
</cfoutput>

Results

enter image description here

See: https://cffiddle.org/app/file?filepath=f9d44f3a-5711-456e-b25a-bf31fead1fa8/6677fc2a-f41b-47d7-b11a-352575f95738/4e1ecc15-ac98-450f-a7fe-b28cf395b012.cfm

0
Adrian J. Moreno On

You have some form.cfm that is making an Ajax request to data.cfm. The data file should return JSON to the JavaScript in the form file.

The data.cfm file basically needs to do this:

<cfscript>
data = {
    a: 1,
    b: 2,
    c: 3
};

cfcontent(type="application/json; charset=UTF-8")
writeOutput(serializeJSON(data))
</cfscript>

The cfcontent function tells the browser that the content being returned is JSON. Without that, it's just a string and you'd have to do more with JavaScript to make sense of the string.

The data returned will look like

{"A":1,"B":2,"C":3}

since ColdFusion stores struct keys in uppercase. In order to make the data return as lowercase keys, you can do either

data = {};
data["a"] = 1;
data["b"] = 2;
data["c"] = 3;

or

data = {
    "a": 1,
    "b": 2,
    "c": 3
};

which will then return the JSON with lowercase keys.

{"a":1,"b":2,"c":3}