XMLHttpRequest on error Examples - Purwana Tekno, Software Engineer
    Media Belajar membuat Software Aplikasi, Website, Game, & Multimedia untuk Pemula...

Post Top Ad

Sabtu, 04 Maret 2023

XMLHttpRequest on error Examples

Example 1:


In this example, we will use the XMLHttpRequest object to send a request to a non-existent URL. When the request fails, the onerror event is triggered, and an error message is displayed in the console.



<!DOCTYPE html>
<html>
<head>
	<title>XMLHttpRequest onerror Example</title>
</head>
<body>
	<button onclick="sendRequest()">Send Request</button>

	<script>
		function sendRequest() {
			var xhr = new XMLHttpRequest();
			xhr.open('GET', 'http://example.com/non-existent-file.txt', true);

			xhr.onload = function() {
				console.log('Response:', xhr.responseText);
			};

			xhr.onerror = function() {
				console.error('An error occurred while processing the request.');
			};

			xhr.send();
		}
	</script>
</body>
</html>


Example 2:


In this example, we will use the XMLHttpRequest object to send a request to an external URL. If the server is down or there is a network issue, the onerror event is triggered, and an error message is displayed in the console.




<!DOCTYPE html>
<html>
<head>
	<title>XMLHttpRequest onerror Example</title>
</head>
<body>
	<button onclick="sendRequest()">Send Request</button>

	<script>
		function sendRequest() {
			var xhr = new XMLHttpRequest();
			xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);

			xhr.onload = function() {
				console.log('Response:', xhr.responseText);
			};

			xhr.onerror = function() {
				console.error('An error occurred while processing the request.');
			};

			xhr.send();
		}
	</script>
</body>
</html>


In this example, we are sending a GET request to an external URL, which returns a JSON response. If the request fails due to any reason, the onerror event is triggered, and an error message is displayed in the console. This can be useful to handle errors and exceptions in an XMLHttpRequest request. 

Post Top Ad