JSON web service example

Click Here

The web service "contacts.php" queries the database and generates data retrieved JSON data format.

File "contacts.php"

<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); $conBD = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $resultBD = $conBD->query("SELECT firsName, lastName FROM Contacts"); $out = "["; while($res = $resultBD->fetch_array(MYSQLI_ASSOC)) { if ($out != "[") {$out .= ",";}; $out .= '{"firsName":"' . $res["firsName"] . '",'; $out .= '"lastName":"'. $res["lastName"] . '"}'; } $out .="]"; $conBD->close(); echo($out); ?>

The following web page "result.html" consumed the previous web service to display data from the database "Contacts".

File "result.html"

<!DOCTYPE html> <html> <body> <h1>Contacts</h1> <div id="divdata"></div> <script> var xmlhttp = new XMLHttpRequest(); var url = "datos.txt"; function myTransform(arr) { var out = ""; var i; var out = "<table>"; out += "<tr><th>FirstName</th>"; out += "<th>LastName</th></tr>"; for(i = 0; i < arr.length; i++) { out += "<tr>"; out += "<td>"; out += arr[i].firstName + "</td><td>"; out += arr[i].lastName + "</td>"; out += "</tr>"; } out += "</table>”; document.getElementById("divdata").innerHTML = out; } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var myData = JSON.parse(xmlhttp.responseText); myTransform(myData); } } xmlhttp.open("GET", url, true); xmlhttp.send(); </script> </body> </html>

The response in the web browser will be:

json webservices example result

The source code of the result will be:

<!DOCTYPE html> <html> <body> <h1>Contacts</h1> <table> <tr><th>FirsName</th><th>LastName</th></tr> <tr><td>Adam</td><td>Smith</td></tr> <tr><td>Anne</td><td>Davis</td></tr> <tr><td>Bruce</td><td>Harris</td></tr> <tr><td>David</td><td>Lee</td></tr> </table> </body> </html>

Click Here