I want to capture a user's postal code in order to retrieve the representatives for that area. To troubleshoot, I am trying to log the postal code and the URL containing the postal code.
$(document).ready(function() {
//When the user submits a postal code (e.g. K2H6G7)
$("form").on("submit", function(event) {
var request = new XMLHttpRequest();
event.preventDefault();
var searchWord = $("#search").val(); //Get postal code and add it to URL
var url = "https://represent.opennorth.ca/postcodes/" + searchWord + "/?format=apibrowser";
console.log(searchWord);
console.log(url) request.open('GET', url, true);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
//Connect to API, create cards for each politician instance
var data = JSON.parse(this.response);
data.representatives_centroid.forEach(representatives_centroid => {
const card = document.createElement('div');
card.setAttribute('class', 'card');
const img = document.createElement('img');
img.src = representatives_centroid.photo_url;
const p1 = document.createElement('p');
p1.textContent = `$ {
representatives_centroid.party_name
}
$ {
representatives_centroid.elected_office
}
$ {
representatives_centroid.first_name
}
$ {
representatives_centroid.last_name
}
`
const p2 = document.createElement('p');
p2.textContent = `$ {
representatives_centroid.district_name
}
` //Add data to card
container.appendChild(card);
card.appendChild(img);
card.appendChild(p1);
card.appendChild(p2);
});
} else {
console.log('error');
}
}
}
request.send();
}
());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form">
<form type="text" class="form-inline" role="form">
<label for="address" name="postalcode">Enter an address or postal code</label>
<input id="search" placeholder="Enter an address or postal code" type="text">
<button id="go">
<span class="glyphicon glyphicon-search"></span> Find
</button>
</form>
</div>
I keep getting the error message "TypeError: event is undefined". Is there something obvious that I'm missing?