Fetch Direct Examples
Fetch examples for various situations that have come up
Post: File data as form data (async/await)
<script>
async function extractZipFile(zipFile) {
try {
const formData = new FormData();
formData.append("upload_file", zipFile);
const response = await fetch(`https://<taregt_url>/extract_details`, {
method: "POST",
body: formData,
});
const fileDetails = await response.json();
if (!response.ok) {
console.log(fileDetails);
return;
}
const fileDetailText = JSON.stringify(fileDetails, null, 2);
console.log(fileDetailText);
} catch (error) {
console.error(error);
}
}
</script>
Post: Json data (await/async)
<script>
async function getDirectPrice() {
try {
if ((directPriceUrl || "").length == 0) {
return;
}
const targetRequest = {
target_url: getPriceUrl(),
watermark: "API_KEY"
};
const response = await fetch(`https://<target_url>/retrieve_price`, {
headers: {
"accept": "application/json",
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify(targetRequest)
});
const fileDetails = await response.json();
if (!response.ok) {
console.log(fileDetails);
return;
}
const fileDetailText = JSON.stringify(fileDetails, null, 2);
console.log(fileDetailText);
const displayPriceDiv = document.getElementById("directPricePane");
directPricePane.innerHTML = "";
let content = document.createElement("PRE");
content.innerHTML = fileDetailText;
directPricePane.appendChild(content);
} catch (error) {
console.error(error);
}
}
</script>
Post: JSON data (Promises)
<script>
function disableCharges(selectedElements)
{
if (selectedElements.length <= 0) {
return;
}
const disableRequest = new Request(`${window.location.origin}@Url.Action("Disable", "Charges")`);
fetch(disableRequest, {
method: 'POST',
credentials: 'include',
body: JSON.stringify({ ids: selectedElements}),
headers: {
'__RequestVerificationToken': $("input[name^=__RequestVerificationToken]").first().val(),
'Content-type': 'application/json; charset=UTF-8'
}
})
.then(function(response) {
window.location.href = response.url;
})
.catch((error) => {
showApiErrorsInModal(disableRequest, error);
});
}
</script>
Get: With a Cross Site Verification Token included
<script>
function getSelectedRowIds()
{
return $("td.griddly-select > input:checked")
.map(function() {
return parseInt(this.value);
})
.get()
.filter(k => !isNaN(k));
}
function disableChargesWithCheck()
{
const selectedElements = getSelectedRowIds();
if (selectedElements.length <= 0) {
return;
}
let checkUrl = new URL(`${window.location.origin}@Url.Action("GetLinkedItems", "Charges")`);
selectedElements.forEach(z => {
checkUrl.searchParams.append('ids', z);
});
const disableCheckRequest = new Request(checkUrl.toString());
fetch(disableCheckRequest, {
method: 'GET',
credentials: 'include',
headers: {
'__RequestVerificationToken': $("input[name^=__RequestVerificationToken]").first().val(),
'Content-type': 'application/json; charset=UTF-8'
}
})
.then(function(response) {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(function (data) {
if (!data.hasOwnProperty("Linked")){
showApiErrorsInModal(response, "Error Disabling Charges (Linked field missing)");
return;
}
if (data.Linked.length <= 0) {
disableSurcharges(selectedElements);
return;
}
const warnings = `<ul><li>${data.Linked.map(z => z.Message).join("</li><li>")}</li></ul>`;
bootbox.confirm({
title: "Are you sure?",
message: warnings,
buttons: {
confirm: {
label: '<i class="fa fa-check"></i> Confirm',
className: 'btn-success pull-right'
},
cancel: {
label: '<i class="fa fa-times"></i> Cancel',
className: 'btn-danger btn-default pull-right'
}
},
callback: function (result) {
if (result)
{
disableSurcharges(selectedElements);
}
}
});
})
.catch((error) => {
showApiErrorsInModal(disableCheckRequest, error);
});
}
</script>
Get: Read blob content (file)
<script>
async function loadCachedFile() {
try {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.length == 0) {
return;
}
const externalId = urlParams.get("external_id");
const response = await fetch(`https://<target_url>/get_property_file?external_id=${externalId}`);
const zip_file = await response.blob();
if (!response.ok) {
console.log(zip_file);
return;
}
if (zip_file.type == "application/json") {
console.log("No match");
return;
}
const timestamp = (new Date()).getTime();
const cached_zip_file = new File([zip_file], `${externalId}_${timestamp}.zip`, {type: "application/zip"});
currentFiles = [];
currentFiles.push(cached_zip_file);
configureUploads();
const arrival = urlParams.get("arrival");
if (arrival != null) {
document.getElementById("checkinDate").value = arrival;
}
const departure = urlParams.get("departure");
if (departure != null) {
document.getElementById("checkoutDate").value = departure;
}
setTimeout(() => {
document.getElementById("getFeedPrice").click();
}, 250);
} catch (error) {
console.error(error);
}
}
</script>