In my previous post we were talking about how to create a REST web service. But now we want to build a client and consume this service.

The address was http://localhost/DbUsersApi.php?action=get_user_list and the result was a JSON file:

{“user_list”:[{“userid”:”D3B6F994-1DA5-47FB-8A2A-750A65AAB137″,”firstname”:”Joe”,”lastname”:”Bloggs”},{“userid”:”E19F2EC8-62B9-4C88-84DC-E0D6903177E0″,”firstname”:”John”,”lastname”:”Doe”}]}

We will use a simple HTML file with Javascript.

Consume the service with Javascript:

Create a new file in your WWW folder and name it RestJSClient.html

<!doctype html>
    <head>
        <title>REST API Client</title>
    </head>
    <body>
		OPEN THE JAVASCRIPT CONSOLE TO SEE THE DEBUG LINES
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
		<script>
			$(document).ready(function() {
				$.ajax({
					//The URL of our web service
					url: "http://localhost/DbUsersApi.php?action=get_user_list"
				}).then(function(data) {
		
					//Display the result in the Console
					console.log("Data fetched from web service");
					console.log("Data: " + data);
					
					//Parse the JSON file to an object
					var parsedJson = JSON.parse(data);
					
					//Take the two first users from the list
					for (var i = 0; i < 2; i++) {
						//Display user by user
						var user = parsedJson.user_list[i];
						console.log("user: " + user.firstname + " " + user.lastname);
					}
				});
			});				
		</script>		
    </body>
</html>

Load the HTML file in your browser. If you are in Chrome then click on the menu button, then More Tools and Developer Tools, then select the Console tab.

This is the result from the Console:

Javascript Console