I am writing my code as follows:
var MyLib = (function (window, $, undefined) {
return {
URI: 'http://testpage/API/',
OnSuccess: function (data, status) { },
OnError: function (request, status, error) { },
MakeRequest: function (method, args) {
$.ajax({
type: 'POST',
url: this.URI + '/' + method,
contentType: 'application/json; charset=utf-8',
data: args,
dataType: 'json',
success: this.OnSuccess,
error: this.OnError
});
},
GetSamples: function (data1, data2) {
var args = {
data1: data1,
data2: data2
};
this.MakeRequest('GetTestData', JSON.stringify(args));
}
};
} (this, jQuery));
So that if I want to invoke the AJAX call, I would do:
function OnSuccess(data, status) {
// ...
}
function OnError(request, status, error) {
}
MyLib.OnSuccess = OnSuccess;
MyLib.OnError = OnError;
MyLib.GetSamples("data1", "data2");
I don’t want to change the signature of GetSamples and therefore I have chosen to implement it as above. Any suggestions on whether this is an acceptable approach (or how to improve this)?
You could also return the jQuery AJAX object and invoke .done() on it where you consume the request.
Like:
And then:
These are called jQuery deferreds, take a look at the API. IMO it’s a very clean way to work with async calls.