HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Ajax for RESTful web service

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
ajaxserviceforrestfulweb

Problem

I wrote an Ajax function, which should be used in a framework to interact with a webserver.

The (self-written) Java-Webserver can be used to fetch files and folder-contents, create files and folders, and delete them.

```
/**
* Performs an Ajax-Request
* @param {string} method HTTP-Method
* @param {string} url
* @param {string} postData optional; HTTP-body
* @param {string} contentType optional; default: "multipart/form-data"
* @param {object} authentication optional; loginCredentials for basicAuth; {"user": "userName", "password": "password"}
* @param {function} callback optional; called, if the operation succeeded;
* Parameter: (string) response-body
* @param {function} errorCallback optional; called, if the operation failed;
* Parameter: 1 = (number) statusCode; (==0, if the given parameters were invalid)
* 2 = (string) statusText; (or errorMessage, if statusCode == 0)
*/
function ajax(method, url, postData, contentType, authentication, callback, errorCallback) {
if(typeof(errorCallback) != 'function'){
errorCallback = function(){}; //Dummy-function to reduce code
}

//Validate the input parameters
if(["GET", "HEAD", "POST", "PUT", "DELETE"].indexOf(method) < 0){
return errorCallback(0, "Invalid method");
}
if(postData && ["HEAD", "POST"].indexOf(method) < 0){ //Other methods don't support postData
return errorCallback(0, "Invalid method for postData");
}
//Get a cross-browser XML-HTTP-Object:
var req = createXMLHTTPObject();
if (!req) {
return errorCallback(0, "Ajax is not supported"); //Oops! Something bad happened
}
req.open(method, url, true); //async = true
//Manipulate header-fi

Solution

Support for JSONP and CORS is a must for any modern web framework.

APIwise, I think you'd want to reduce the arguments to your method to a single object, similar to how jQuery does it. It gives an opportunity to give defaults, and simplifies it from the API perspective. As it stands, it will be painful to use, in that you need to remember a lot of arguments. A simple GET ajax with your's:

ajax('GET', 'index.html', null, null null function(evt) {
    console.log("Success!")
})


vs jQUery or similar:

ajax({method:'GET', url:'index.html'}, success:function(evt) {
    console.log("Success!")
})

Code Snippets

ajax('GET', 'index.html', null, null null function(evt) {
    console.log("Success!")
})
ajax({method:'GET', url:'index.html'}, success:function(evt) {
    console.log("Success!")
})

Context

StackExchange Code Review Q#57518, answer score: 3

Revisions (0)

No revisions yet.