Show how to create a small reusable function. We have to call the API always. If I make this complex API function once, I can use it again and again. How will it be?

async function CallAPI(url, method = "GET", data = {}) {
try {
let res = await $.ajax({
url: url,
type: method,
data: data,
dataType: "json"
});
return res;
} catch (err) {
console.error("Ajax Error:", err);
return { status: "error", message: "Request failed" };
}
}
// Uses:
(async () => {
let res = await CallAPI("api/delete.php", "POST", { id: 5 });
if (res.status === "success") {
alert("Deleted");
} else {
alert("! " + res.message);
}
})();

Now, if you want, let Res = CallAPI(“URL”); You can write or set the data gate from the API. But you will not get an instant response (async) has been used.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply