RESTful calls via AngularJS

I’ve been doing more with AngularJS lately, it’s becoming really popular. Here’s how to do RESTful calls with Angular:

var config = {headers:{'accept': 'application/json',
    'content-type': 'application/json;charset=UTF-8'}};
    
$http.post(url, data, config).
    success(function(response)
    {
        successHandler(response);
    }).
    error(function(response)
    {
        errorHandler(response);
    });

RESTful calls via JQuery

I created a post showing hoe to make RESTful calls with plain vanilla JavaScript and wanted to show how to do the same thing using JQuery. So here it is:

RESTService.prototype.doPost = function(url, data, successHandler, errorHandler)
{
    $.ajax(
    {
	data: JSON.stringify(data),
	dataType: 'json',
	type: 'POST',
	url: url,
	beforeSend: function(request)
	{
	    request.setRequestHeader('accept', 'application/json');
	    request.setRequestHeader('content-type', 'application/json;charset=UTF-8');
	},
	success: function(response)
	{
            successHandler(response);
    	},
	error: function(response)
        {
            errorHandler(response);
	}
    });
};

RESTful calls via JavaScript

I’ve been doing a lot more front-end work with JavaScript lately and have needed to make calls to RESTful APIs. One of my complaints with JavaScript is that it feels like there is not a standard way of doing things. One can always do things the plain old JavaScript way or one can use one of the many frameworks that exist. This post focuses on the plain vanilla way to use JavaScript to access a RESTful web service API. The following is a sample function that makes a POST call:

RESTService.prototype.doPost = function(url, data, successHandler, errorHandler)
{
    var http = new XMLHttpRequest();

    http.open("POST", url, true);
    http.setRequestHeader("accept", "application/json");
    http.setRequestHeader("content-type", "application/json;charset=UTF-8");

    http.onreadystatechange = function()
    {
        if(http.readyState == 4)
	{
	    if(http.status == 200)
	    {
                successHandler({});
	    }
            else
            {
                errorHandler({});
            }
	}
    };
    http.send(JSON.stringify(data));
};

To change what type of call just change the “POST” to “GET” etc.