Php Restful Service for Get, web client

service and web client

home

The scenario to access a resful service with get request is as below:

part 1. php service code for get


- Php service data can be for both rest call or not rest call.
- It depends on how a client calls.
- Because of this, I use not rest call to test.
- After the call, use browse back to get back.

preparing MySql data with php

    1   $servername = "xxxx.com";
    2   $username = "xxxxx";
    3   $password = "xxxxx";
    4   dbname = "xxxxxr";
    5   $conn = mysqli_connect($servername, $username, $password, $dbname);
    6   if (!$conn) { die("Connection failed: " . mysqli_connect_error());}
    7   $sql = "SELECT dog_name, dog_color FROM dogs";
    8   $result = mysqli_query($conn, $sql);
    9   mysqli_close($conn);
    10  $arr = array();
    11  while($row = mysqli_fetch_assoc($result)) {
             array_push($arr, $row);   
    12  };
    13  $jsonStrData = json_encode($arr);
    14  echo $jsonStrData;
    
    --- code review ---
    1      A php variable is prefixed with $. 
    1      Its type is set during assigning its value.
    5      mysql_connect is language extention, mysqli procedure.
    8      return a mysqli_result object.
    10-12  convert into a Php assocaite array from $result .
    13     convert the array into a string in json format.
    14     php uses echo to return data, one way, it is simple. 
    14     Nodejs has many ways.
    
    ---  data from a string, not database, add two lines inside php tags.
    $data = '[{"dog_name":"Tairo","dog_color":"brown"},{"dog_name":"Emi","dog_color":"white"}]';
    echo $data;  
            

part 2. web rest client

- jquery takes care of the network task
- using javascript
<script> $(document).ready(function () { // after DOM is ready $("#btnGet").click(function () { // jq selector's method // jquery method, callback from the web server $.get("5_data.php", function (data, status) { alert("Data: " + data + "\nStatus: " + status); $("#msg").html(data); // rendering data $("#msg2").html(status); // render the http status }); }); }); </script>

data from rest get

http status for rest get