Archive for November, 2009

Create a Simple JSON Web Service with PHP and JQuery

Here’s what you need to get started creating a simple JSON Web Service with PHP and JQuery. You’ll need to download JQuery and include it in your page as I’ve done.

The HTML page just has a couple of links that are hooked up to JQuery methods which post values to a PHP page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<html>
 
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script src="jquery-1.3.2.js" type="text/javascript"></script>
 
<script type="text/javascript">
 
        $(document).ready(function () {  //The DOM is now loaded and can be manipulated.
 
          //Wire up the divs to do stuff whenclicked
          $("#CallAddPost").click(function () {
              callAddPost();
          });
 
 
          $("#CallMultiplyAjax").click(function () {
              callMultiplyAjax();
          });
 
          //Option1: Use JQuery Post Method. Two Parameters. First Parameter is
          //the functionName.  Second Parameter is a json-formatted string
          function callAddPost(){
                   $.post("jsontest.php",
                   {functionName: 'add',params:'{"first":8, "second":2}'},
                   function(data){
                       alert(data);
  	         }
              );
          }
 
          //Option 2: Use JQuery Ajax Method.
            function callMultiplyAjax(){
            $.ajax({
                  url: "jsontest.php",
                  global: false,
                  type: "POST",
                  data: {functionName : "multiply",params:'{"first":8, "second":2}'},
                  dataType: "html",
                  success: function(data){
                     alert(data);
                  }
               }
            );
          }
 
        });// //End Document Ready
 
</script>
 
</head>
 
<body>
    <a href="#" id="CallAddPost">Call Add Post</a>
    <a href="#" id="CallMultiplyAjax">Call Multiply Ajax</a>
</body>
 
 
</html>

The PHP Script reads the values posted from the HTML page and calls one of two methods based on which method is specified in the POST.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
 
function add($par) {
    $result = 0;
    //You see we can loop through the parameters irrespective of key
    foreach($par as $key=>$val) {
        $result += $val;
    }
    return array("result"=>$result);
}
 
function multiply($par) {
    //Here we reference the variables in the array by their keys
    $result = $par['first'] * $par['second'];
    return array("result"=>$result);
}
 
$postmethod = $_POST["functionName"];  //Gets the 'functionName' string value from the POSTed json
$params = $_POST["params"];    //Gets the 'params' string value from the POSTed json
 
//Turn the json string of parameters into an associative array
$params = json_decode($params,true); //true means we're creating an array (not an object)
 
$functionCall = $postmethod."(\$params);";
eval("\$retObj=".$functionCall.";");
 
//Echo sends the result back to the page
 
echo $retObj['result'];  //If I just want to return the result, I don't have to json encode it
//Otherwise, if I want to return the array, I just use the json_encode method to turn the array into JSON
?>

Here are some useful links:
http://docs.jquery.com/Ajax
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php

Leave a Comment