javascripthtmlcanvasserverside-javascriptexacttarget

Using Server Side JavaScript and trying to get the properties of an element on my DOM


I'm using Server Side JavaScript to interact with our data. For example:

<script runat="server">
        var subscriberScoringHistoryDE = DataExtension.Init("de_name");
        var rows = subscriberScoringHistoryDE.Rows.Retrieve();
        for (var i = 0; i < 5; i++)
        {

        }
</script>

The above will run because it's hitting a JS API that's on our server. So anyways, the above runs fine. The problem I'm having is if I have something like the below in conjunction with the above:

<script>
        var barChartData = {

            // labels will be the dates
            labels : ["January","February","March","April","May","June","July"],
            datasets : [
                {
                    fillColor : "rgba(220,220,220,0.5)",
                    strokeColor : "rgba(220,220,220,1)",

                    // data will be the count
                    data : [65,59,90,81,56,55,40]
                },  
            ]
        }

    var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);

    </script>

<body>
    <canvas id="canvas" height="450" width="600"></canvas>
</body>

The JS code will not see anything called "canvas". I even tried putting runat="server" on my canvas. I can imagine this is because it's looking at the server for an ID called "canvas" and not my client side DOM, am I correct in assuming this?

Is it possible to intermingle client-side JavaScript and server-side JavaScript? How can I get my JavaScript to see the canvas that's on my client COM?


Solution

  • You need to wrap your main script in an onload type handler, so it'll only run AFTER the dom has been loaded/parsed. One quick/dirty way of doing it is

    <script>
       function foo() {
          // your var barchartdata etc... goes here
       }
    </script>
    
    <body onload="foo();">
    ....
    </body>
    

    If you were using jquery, you'd get a somewhat more reliable

    $(document).ready(function() {
       /// var barchartdata stuff goes here
    });
    

    As for mingling the client-/server-side code, not really possible, since they execute in totally different environments. client-side JS code can't directly call on server-side code, and server-side code can't call client-side code, because JS calls cannot pass through an HTTP layer. You COULD use an ajax call to indirectly call things, but then you're still using HTTP.