Pages

Tuesday, 5 March 2013

AJAX using Angular JS

Angular JS defines a service, $http, that is capable of communicating with remote servers over HTTP using XmlHttpRequest. $http includes a service that takes a single configuration object where we configure all required properties for the remote asynchronous call. Following is the syntax of using $http service with configurations:

$http({method:’<method>’, url: ‘<service-url>’})
.success(function(data, status, headers, config){
//Logic to be executed upon successful completion of the request
//Will be called asynchronousy
})
.error(function(data, status, headers, config){
//Logic to be executed when the request is unsuccessful
//Will be called asynchronously
});

We also have shortcut methods to send get, post, put, delete, head and JSONP requests. These methods accept URL, config. Post and put methods accept input data also as a parameter. To learn more about these methods and the input parameters, refer to $http service documentation.

Let’s continue with our shopping cart example which I have used in all earlier posts (Last post in this series is Form validation using Angular JS). I created an ASP.NET Web API controller to operate on the cart items. We have to replace the logic of operating with cart items with AJAX calls to the Web API. I chose Web API to create the services because it makes creation and consumption of HTTP services very easy. If you are new to Web API, checkout Web API content on official ASP.NET website.

Following are the ShoppingCartItem and ShoppingCart classes, these classes are used to define structure of each item and to operate on the current items on the cart respectively.

I am using the shorthand get method of http service here. We can obtain the same result using $http(options) as well.
For the time being, I am placing the logic of AJAX calls in Controller to make the demo simple. We will move it into a module in another post. Following is the modified controller:

About Me

I am a software developer working on and passionate about Microsoft Technologies and anything new in the Web world. Lately, spending a lot of time with JavaScript and finding it much deeper than what I knew for past few years. I enjoy writing code and writing about code. My contribution to community earned me a Microsoft MVP award (ASP.NET/IIS) and a DZone MVB award. When not in front of computers, like to spend time with melodious Hindi and Telugu tunes or watching Cricket