Post raw R code as argument to function call

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>
<h1>Posting Code Snippets</h1>

x: <input type="text" id="input" value="rnorm(1000)"> <br> <br>
<button id="submitbutton" type="button">Calc mean</button>

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

JavaScript

//because plot is in graphics
ocpu.seturl("//public.opencpu.org/ocpu/library/base/R")

//actual handler
$("#submitbutton").on("click", function(){
    
    //create snippet argument
    var x = new ocpu.Snippet($("#input").val());
    
    //disable button
    $("button").attr("disabled", "disabled");

    //perform the request
    var req = ocpu.call("mean", {
        "x" : x
    }, function(session){
        session.getConsole(function(outtxt){
            $("#output").text(outtxt); 
        });
    });
        
    //if R returns an error, alert the error message
    req.fail(function(){
        alert("Server error: " + req.responseText);
    });      
    
    req.always(function(){
        $("button").removeAttr("disabled");    
    });
});