Get fields and output from a session

by opencpu

HTML

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//cdn.opencpu.org/opencpu-0.4.js"></script>
<button id="postbutton" type="button">Test!</button> <br><br>

Session ID: <tt id="key"></tt> <br >
Session Location: <tt id="location"></tt> 

<pre><code id="output"></code></pre> 

<button id="getbutton" type="button" disabled="disabled">Get Object</button> 
<button id="varbutton" type="button" disabled="disabled">Calculate Variance</button>

CSS

pre {
    border: solid gray 1px;
    padding: 5px;
    margin: 10px;
}

JavaScript

//set CORS to call "appdemo" package on public server
ocpu.seturl("//public.opencpu.org/ocpu/library/stats/R")

//global var
var mysession;

//calls R function: stats::rnorm(n=100, mean=runif(1)):
$("#postbutton").click(function(){
    var rnd = Math.random();
    var req = ocpu.call("rnorm", {n: 100, mean:rnd}, function(session){
        //assign to global var
        mysession = session;
        
        //read the session properties (just for fun)
        $("#key").text(mysession.getKey());
        $("#location").text(mysession.getLoc());
        
        //retrieve session console (async)
        mysession.getConsole(function(outtxt){
            $("#output").text(outtxt);
        });
        
        //enable the other button
        $("button").removeAttr("disabled");
    }).fail(function(){
        alert("Error: " + req.responseText);
    });
});

$("#getbutton").click(function(){
    //retrieve object (async)
    mysession.getObject(function(data){
        //data is the object returned by the R function
        alert("Array of length " + data.length + ".\nFirst few values:\n" + data.slice(0,5).join("\n")); 
    });
});        

$("#varbutton").click(function(){
    //calculate the var of the previous object
    var req = ocpu.call("var", {x : mysession}, function(session){
        
        //retrieve output
        session.getObject(function(data){
            alert("Variance of object " + mysession.getKey() + " equals: " + data);
        });
    }).fail(function(){
        alert(req.responseText);  
    });
});