Using ocpu.rpc to do simple JSON rpc

by dm89

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="submitbutton">Run T-TEST</button> <br>

<pre><code></code></pre>

CSS

pre {
    position: relative;
    height: 50px;
}

JavaScript

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

//some example data
//to run with different data, edit and press Run at the top of the page
var x = [1,2,3,4,5,6,7,8,9,10];
var y = [7,8,9,10,11,12,13,14,15,16,17,18,19,20];

//call R function: stats::var(x=data)
$("#submitbutton").click(function(){
    
    var req = ocpu.call("t.test",{
        x : x,
        y : y
    }, function(session){
      //retrieve session console (stdout) async
      session.getConsole(function(outtxt){
          //$("code").text(outtxt);
          var stIdx = outtxt.search("p-value = ");
          //$("code").text(stIdx);
          var endIdx = outtxt.indexOf('\n', stIdx+10);
          var pvalue = outtxt.substring(stIdx+10, endIdx);
          $("code").text(pvalue);
      });
    });

    //optional
    req.fail(function(){
        alert("R returned an error: " + req.responseText); 
    });
});