Core JavaScript

Get JSON Labyrinth with AJAX

This JavaScript program shows how to fetch a PHP generated JSON labyrinth via an AJAX call.

GetJsonLabyrinth.html

<!DOCTYPE html>
<html>
	<head>
		<title>XoaX.net: PHP Labyrinth</title>
		<link rel="icon" href="data:,">
	</head>
	<body>
		<script language="javascript" type="text/javascript">
			// This requires a web server
			let qHttpRequest = new XMLHttpRequest();
			// Method, URL, Async
			qHttpRequest.open("GET", "Labyrinth.php", true);

			qHttpRequest.onload = function( e ) {
				let iaaGrid = JSON.parse(this.response);
				let qGridDiv = document.getElementById("idGrid");
				console.log(iaaGrid);
				for (let iRow = 0; iRow < iaaGrid.length; ++iRow) {
					let dRowPercent = 100/iaaGrid.length;
					let qGridRow = document.createElement("div");
					qGridDiv.appendChild(qGridRow);
					qGridRow.style.width = "100%";
					qGridRow.style.height = dRowPercent+"%";
					qGridRow.style.position = "absolute";
					qGridRow.style.top = dRowPercent*iRow+"%";
					qGridRow.style.left = "0%";
					for (let iCol = 0; iCol < iaaGrid[iRow].length; ++iCol) {
						let dColPercent = 100/iaaGrid[iRow].length;
						let qGridCell = document.createElement("div");
						qGridCell.style.width = dColPercent+"%";
						qGridCell.style.height = "100%";
						qGridCell.style.position = "absolute";
						qGridCell.style.top = "0%";
						qGridCell.style.left = dColPercent*iCol+"%";
						if (iaaGrid[iRow][iCol] == 1) {
							qGridCell.style.backgroundColor = "#DDDDDD";
						} else {
							qGridCell.style.backgroundColor = "#888888";
						}
						qGridRow.appendChild(qGridCell);
					}
				}
			};
			qHttpRequest.send();
		</script>
		<div id="idGrid" style="position:absolute; width:800px; height:800px; border: 1px black solid;"></div>
	</body>
</html>

Labyrinth.php

<?php
header('Content-type: text/javascript');


$iaaLabyrinth = [
	[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
	[1, 0, 0, 1, 1, 0, 0, 0, 0, 1],
	[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
	[1, 0, 0, 1, 1, 0, 0, 0, 0, 1],
	[1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
	[1, 0, 0, 1, 1, 0, 0, 0, 1, 1],
	[1, 0, 0, 1, 1, 0, 0, 0, 1, 1],
	[1, 0, 0, 1, 1, 0, 0, 0, 0, 1],
	[1, 0, 0, 0, 0, 0, 1, 0, 0, 1],
	[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];

echo json_encode($iaaLabyrinth);
?>
 
 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.