Search code examples
phpjavascriptjsonxmlhttprequestrpc

Using JavaScript for RPC (Remote Procedure Calls)


Whats the best way to do a RPC (Remote Procedure Call) from a webpage or from JavaScript code? I want to keep it in JavaScript if possible so that I can do live updates to the webpage without having to do anything in PHP in case my server goes down I still want the JavaScript to handle page updates... possibly even sending a request to a python shell script running locally... Is this legal from JavaScript?

I prefer having remote machines handling the requests. I see a lot of talk about how XMLRPC or JSONRPC can do this however, I haven't seen any good examples. I guess Microsoft suggests using their XMLhttprequest however, I haven't seen anything that doesn't use their ActiveX call or require special code for Internet Explorer... I just want some simple way of passing a command to some python/ruby/c++ code from a webpage.

Python Server Code (Waiting for a RPC Request):

import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
def my_awesome_remote_function(str):
    return str + "awesome"
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.serve_forever()

EXAMPLE JavaScript Code:

var client = rpc.server("http://localhost:8000/");
var my_local_variable = client.my_awesome_remote_function(param);

Is there a good JSON/JavaScript example someone can point me to that sends a request to a server and gets some data back from that server?

Thanks!


Solution

  • Hardly it will work this way: client.my_awesome_remote_function. There's no magic in js like __call in php. Also remote calls are done in js mostly asynchronously using idea of callback - function which is called after finishing of some task.

    var client = rpc.server("http://localhost:8000/");
    var my_local_variable;
    client.rpc('my_awesome_remote_function', [param], function(result) {
        my_local_variable = result;
    });
    

    You can easily find tutorials about that calls. Just google "ajax tutorials". E.g.: http://www.w3schools.com/ajax/ajax_intro.asp (event though w3schools isn't the best site and have errors in some details, it is still good for beginners).

    All ajax implementations use both modern both XMLHttpRequest and ActiveX control for older IE.

    It is possible to run those requests synchronously, but is considered very bad from the point of user experience. Also, you'll need to deal with concept of callbacks anyway.