Getting Null Value ajax request

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<link rel="shortcut icon" href="#">
	<style>
		button {
			padding: 10px 15px;
			font-size: 25px;
			font-weight: bold;
			border: none;
		}
	</style>
</head>
<body>
	<main>
		<h1>AJAX</h1>
		<div id="ouput"></div>
		<button id="loadnew">Click Me</button>
	</main>

	<script type="text/javascript">
		var output = document.getElementById('output');
		var buttonClick = document.getElementById('loadnew');
		buttonClick.addEventListener('click',function(){
			loadAjax();
		});
		function loadAjax(){
			var ajax = new XMLHttpRequest();
			// ajax.open('GET','https://randomuser.me/api/',true);
			// ajax.send('');
			ajax.onreadystatechange = function(){
				// console.log('state changed',ajax.readyState, ajax.status)
				if(ajax.readyState==4 && ajax.status==200){
					var json = JSON.parse(ajax.responseText);
					var data = json.results[0];
					console.log(data);
					var message = data.name.first+''+data.name.last;
					console.log(message);
					output.innerHTML = message;					
				}
			}	
			ajax.open('GET','https://randomuser.me/api/',true);
			ajax.send();	
		}
		
		/*ajax.onprogress = function(){
			console.log('progress',ajax.readyState, ajax.status)			
		}
		ajax.onload = function(){
			console.log('DONE',ajax.readyState, ajax.status)			
		}
		console.log(ajax);
		*/
		
	</script>
</body>
</html>

I am getting a warning:

(index):41 Uncaught TypeError: Cannot set property 'innerHTML' of null
    at XMLHttpRequest.ajax.onreadystatechange ((index):41)

output.innerHTML = message;

That means message object is not getting value but NULL or NAN.
where am I going wrong?

Grammatic error in ID: <div id="ouput"></div>

Any time, if you get error like “DOM-element not found”, check at first its ID, Name and so on…

1 Like

Right, that was nontechnical, but a silly mistake.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.