Skip to content

Instantly share code, notes, and snippets.

@bertzzie
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bertzzie/cca44a45bfed354e63b4 to your computer and use it in GitHub Desktop.
Save bertzzie/cca44a45bfed354e63b4 to your computer and use it in GitHub Desktop.
Implementasi AJAX mirip $.ajax jQuery.
var MyLib = MyLib || {};
MyLib.AJAX = function (options) {
if ("method" in options &&
"url" in options &&
"onSuccess" in options) {
var xhr,
method = options.method,
data = options.data,
url = options.url,
async = options.async || true,
onSuccess = options.onSuccess,
onFailure = options.onFailure || function () { };
try {
xhr = new XMLHttpRequest();
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr === undefined) {
alert("TIDAK MENDUKUNG AJAX");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
onSuccess(xhr.responseText);
} else {
onFailure();
}
}
};
xhr.open(method,
url,
async);
xhr.send(data);
} else {
alert("Options tidak lengkap");
}
};
// Contoh penggunaan
var HandleData = function (data) {
// do something
};
var HandleError = function () {
// do something
};
var LogBaru = function (data) {
// do something
};
MyLib.AJAX({
method : "GET",
url : "http://contoh.com/ajaxapi/departments",
async : true,
onSuccess : HandleData,
onFailure : HandleError
});
MyLib.AJAX({
method : "POST",
url : "http://contoh.com/ajaxapi/departments/" + dept_no,
async : true,
onSuccess : LogBaru,
onFailure : HandleError
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment