In this post, we will see how we can consume WebApis in Javascript. We do it via creating a windows 8 Javascript application. It's been long since I haven’t written any post, was quite busy lately. You know breakup–patchup breakup-patchup, kind of headache. Believe me folks, if your girlfriend is happy, then you are happy, and if she is unhappy, woo! you better start praying.
So WebApis, as we have discussed in the preceding post how WebApis can be created, also we have seen how to make a GET request from browser. Now we will have a look at how to make that call from Javascript instead and many more.
Adding Windows 8 Application Project
The first step is to add the windows 8 application project to the solution.
Name the application to something suitable like, “HelloApiWindows8” kind of. Once the project is added, we are good to go.
What we are up to?
What we are going to do is to make a GET call to the Api, and display the result it return on the UI. In order to keep everything crisp, let’s take a button on the UI through which we will initiate the api call. Add the following code in the body tag of default.html.
1: <body>
2: <h1>Web Api Demo</h1>
3: <br /><br />
4: <button id="btnStart">Click Me</button>
5: <div id="contentApi"></div>
6: </body>
In the JavaScript file, i.e. default.js, we will create the button click event listener like this.
1: app.onactivated = function (args) {
2: if (args.detail.kind === activation.ActivationKind.launch) {
3: if (args.detail.previousExecutionState !==
4: activation.ApplicationExecutionState.terminated) {
5: //Start button click event listener
6: document.getElementById('btnStart').addEventListener('click',
7: StartButtonClick, false);
8: } else {
9: // TODO: This application has been reactivated from suspension.
10: // Restore application state here.
11: }
12: args.setPromise(WinJS.UI.processAll());
13: }
14: };
Now on button click, we need to make the GET request to the WebApi. Here is the important point. The call to the WebApi should be asynchronous. Meaning UI should not freeze while completing the call, as the communication will take place over the internet, which might cause some delay and it would be a bad user experience if the UI freezes. That call therefore will be an Ajax call.
So, in the StartButtonClick() function, let’s make the ajax GET request to the Api.
1: function StartButtonClick(){
2: $.ajax({
3: url: 'http://localhost:42055/api/values',
4: type: 'GET',
5: contentType: "application/json",
6: success: function (data) {
7: for (var i = 0; i <= data.length-1; i++) {
8: var content = document.getElementById('contentApi');
9: var para = document.createElement("p");
10: var node = document.createTextNode(data[i]);
11: para.appendChild(node);
12: content.appendChild(para);
13: }
14: }
15: });
16: }
Now let’s understand what each line does. First url specifies the url of the api, as we have seen in the previous post as of how to get one. Type specifies the type of HTTP request we want to make, i.e. being GET, POST, PUT, DELETE. ContentType, it is the on demand request from the client to the api, as in which form the client is expecting the data back. As of now, we are asking Api to return data in JSON format.
Next is Success. It’s a listener that listens the return result from the api. Whenever the api successfully returns some queried data, it gets activated. We can access the result which api returns, from the function parameter, data. Now as we are returning an array from Api, we therefore are sure of getting an array back. Hence we iterates over the result and add the values one by one from the array onto the UI, in the form of the Paragraph tags (<p></p>).
If everything went fine, set both the projects as the startup projects, hit F5 and you must see the following result.
Hope you have enjoyed it.
Happy Reading!!!
0 comments