Wednesday, March 12, 2014

HTML 5 tutorial - How to access web service (Web API) from HTML file



In this tutorial, we will go over, how to retrieve data using ajax and display it within our HTML page.

To start with, will create a new ASP.NET empty web application and keep adding files as and when we need to do.

Select New project option from the menu and select the following option :



Once you do that, the solution explorer should be loaded with your empty file structure.



Now lets add a HTML file and call it HTML_API.  The most important task for me to achieve in this HTML will be to invoke a web service using ajax call and display the results within a table structure.


Once the files is created, lets edit the HTML and make necessary changes to make ajax calls. To achieve this, we need to include jQuery within our script tag. This can be achieved in more than one way.


  1. You could either download the file here and include it in your project
  2. You could use any of the CDN's below and refer them online.

 CDN's are nothing but Content Delivery Network. The purpose of CDN is, they host the required files and by referring them, you can still achieve the same output.

Below is a sample of various CDN options (excludes including through physical path).

In our tutorial, I will be using google api's to refer for jQuery. More over, I will be using the same Web API tutorial (which I used for MVC Grid) to display data. 

Below is the ajax code to invoke Web Service from HTML 5 page.

What is being done here is, invoking the web service and on its successful return with data, we are creating a table row and inserting the values within <td> tags. The whole content is finally appended to the table with id "category" and that would complete the getting results displayed within the table tag.

Below is the image for having the table tag as defined above.

Earlier while testing, I had this error occurring and unable to get the data from database. That's when I realized that I needed the following line.

jQuery.support.cors = true;

CORS are nothing but, Cross Origin Resource Sharing and mainly used for Cross-domain requests.

The final result is below:


Happy coding...