Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
Fetch [Go Back]
Back in the day, when you wanted to send data to a web server from javascript, AJAX (XMLHttpRequest) was used. There is a page on this site which goes into detail for using AJAX.

Fast forward to today there is a new method for doing the same thing with newer standards using Fetch (native browser functionality) and combining that with JSON. There are different ways that Fetch can be used, and one of them (simplified) is included below. As you can see, the code footprint is significantly smaller than with traditional AJAX for the request/response:

async function submitData(dataArray) {
	const jsonPayload = JSON.stringify(dataArray);
	try {
		let validationRequest = await fetch("some url", {
			method: "POST",
			mode: "cors",
			cache: "no-cache",
			headers: {
				"Content-type": "application/json"
			},
			body: jsonPayload
		});
		if (!validationRequest.ok) { throw new Error("Network issue"); }
		let validationResponse = await validationRequest.json();
		/* Handle the response data being returned, in this case "info" */
		validationResponse.forEach(vResponse => {
			let responseInfo = vResponse.info.toString();
			alert(responseInfo);
		});
	}
	catch (error) {
		alert("something went wrong.");
	}
}


About Joe