Skip to content

Instantly share code, notes, and snippets.

@ngsankha
Last active December 19, 2015 08:28
Show Gist options
  • Save ngsankha/5925547 to your computer and use it in GitHub Desktop.
Save ngsankha/5925547 to your computer and use it in GitHub Desktop.
Demo JSON-RPC implementation

This is a very simple implementation of the JSON-RPC spec v1 in PHP. Take a look at it at http://json-rpc.org/wiki/specification.

Here what you do from your webapp.

$.post('/rpc.php', {'method': 'echo',
                    'params': ['Hello JSON-RPC'],
                    'id': Math.floor(Math.random()*100)
                   }, function (data) {
                        alert("I received result: " + data.result);
                    , 'json');

On you server side this PHP would give you back the call.

<?php
  function echo(text) {
    return text;
  }

  $method = $_POST['method'];
  $params = $_POST['params'];
  $id = $_POST['id'];
  $error = null;
  if ($method == 'echo')
    $result = echo($params[0]);
  else {
    $result = null;
    $error = 'method not found`;
  }
  $response = array('result' => $result, 'error' => $error, 'id' => $id);
  echo json_encode($arr);
?>

We have just implemented the first example in the spec.

Request: { "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}
Response: { "result": "Hello JSON-RPC", "error": null, "id": 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment