From a6bea55189fb91ab0d2e1c61d82c30c3bf0f51cc Mon Sep 17 00:00:00 2001 From: Dita Aji Pratama Date: Wed, 27 Dec 2023 23:55:31 +0700 Subject: [PATCH] First commit --- README.md | 39 ++++++++++++++++++++++++++++++++++++++- carrack.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 carrack.js diff --git a/README.md b/README.md index 4ba9eab..a0e0cfe 100644 --- a/README.md +++ b/README.md @@ -1 +1,38 @@ -# carrackjs \ No newline at end of file +# CarrackJS + +JS library for a HTTP Requests + +## usage + +Example usage with JSON data: + + var apiUrlJson = "https://example.com/api/json"; + var requestDataJson = { + key1: "value1", + key2: "value2" + }; + + sendHttpRequest(apiUrlJson, "POST", requestDataJson, function (error, response) { + if (error) { + console.error("Error:", error); + } + else { + console.log("JSON Response:", response); + } + }, "application/json"); + +Example usage with non-JSON data (e.g., form data): + + var apiUrlFormData = "https://example.com/api/formdata"; + var formData = new FormData(); + formData.append("key1", "value1"); + formData.append("key2", "value2"); + + sendHttpRequest(apiUrlFormData, "POST", formData, function (error, response) { + if (error) { + console.error("Error:", error); + } + else { + console.log("Form Data Response:", response); + } + }, "multipart/form-data"); diff --git a/carrack.js b/carrack.js new file mode 100644 index 0000000..6ad1f2d --- /dev/null +++ b/carrack.js @@ -0,0 +1,33 @@ +function sendHttpRequest(url, method, data, callback, contentType = "multipart/form-data") { + var xhr = new XMLHttpRequest(); + + xhr.open(method, url, true); + xhr.setRequestHeader("Content-Type", contentType); + + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + if (xhr.status === 200) { + // Successful response + var response; + if (contentType === "application/json") { + response = JSON.parse(xhr.responseText); + } else { + response = xhr.responseText; + } + callback(null, response); + } else { + // Error response + callback(xhr.status, null); + } + } + }; + + var requestData; + if (contentType === "application/json") { + requestData = JSON.stringify(data); + } else { + requestData = data; + } + + xhr.send(requestData); +}