Search code examples
ropencpu

How to use ocpu.r_fun_call?


I am able to use the opencpu function ocpu.rpc. But not the function ocpu_r_fun_call. Why the above code does not work?

<html>
  <head>

    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="//cdn.opencpu.org/opencpu-0.4.js"></script>

    <script>

    $(document).ready(function(){

        $("#submitbutton").click(function(){
          var req = ocpu.r_fun_call("mean", {"x" : 10}, function(session){
            $("#namefield").val(session);
          });
        });

    });

    </script>

  </head>

  <body>

    <input type="text" id="namefield" value="">

    <button id="submitbutton" type="button">Submit!</button>

  </body>
</html>

I also tried:

$("#submitbutton").click(function(){
  var req = ocpu.r_fun_call("mean", {"x" : 10}, function(session){
    session.getObject(function(data){
      $("#namefield").val(data);
    });
  });
});

And I also tried with session.getConsole, and also:

  var req = ocpu.r_fun_call("mean", {"x" : 10}, function(session){
$("#submitbutton").on("click", function(){
    $("#namefield").val(session.getObject());
  });
});

Solution

  • The main problems were:

    • the js function is ocpu.call, not ocpu.r_fun_call

    • the fact that the mean function does not belong to my package. If I put an average function in my package:

      average <- mean

    Then I can use it with opencpu like this:

    <html>
      <head>
        <script src="opencpu/jquery-1.10.2.min.js"></script>
        <script src="opencpu/opencpu-0.4.js"></script>
    
        <script>
    
        $(document).ready(function(){
          $("#submitbutton").on("click", function(){
    
            var req = ocpu.call("average", {
              x : 10
            }, function(session){
              session.getObject(function(data){
                    $("#namefield").val(data)
                  });
            });
    
            //if R returns an error, alert the error message
            req.fail(function(){
              alert("Server error: " + req.responseText);
            });
    
          });
        });
        </script>
      </head>
    
      <body>
    
        <button id="submitbutton" type="button">Submit!</button>
        <input type="text" id="namefield" value="">
    
      </body>
    </html>
    

    Note the tip to know more when there's a problem:

        //if R returns an error, alert the error message
        req.fail(function(){
          alert("Server error: " + req.responseText);
        });