b1nary0mega
5/13/2016 - 1:56 PM

Use AJAX to retrieve and display (without reloading the page) a persons senator, based on their zipcode

Use AJAX to retrieve and display (without reloading the page) a persons senator, based on their zipcode

<html>
<head>
</head>

<body>
<form action="" id="rep-lookup">
  <div>
    <label for="txt-zip">Zip Code:</label>
    <input type="number" id="txt-zip" name="zipcode" required />
  </div>
  <div>
    <input type="submit" id="btn-lookup" value="Look up" />
  </div>
</form>

<div id="rep-lookup-results">
	<em>When data is found, it will be displayed here...</em> 
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 

<script>
'use strict';

$(document).ready(function() {
  $('#rep-lookup').submit(function(e){
		e.preventDefault();
		
		var $results = $('#rep-lookup-results'),
				 zipcode = $('#txt-zip').val()
				 apiKey = '88fea62dc07a487da4d6cf9204e1e609';
			
		var requestURL = 'http://congress.api.sunlightfoundation.com/legislators/locate?callback=?';
		
		// collect the data
		
		$.getJSON(requestURL, {
				'apikey' : apiKey,
				'zip' : zipcode
		},
			function(data){
				//console.log(data);
				if(data.results && data.results.length > 0) {
					var mySenators = '<p>Here are your Senators</p>';
					
					$.each(data.results, function(i, rep) {
						if('senate' === rep.chamber.toLowerCase()) {
							mySenators += '<p>';
							mySenators += '<a href="' + rep.contact_form + '" target="_blank">';
							mySenators += rep.first_name + ' ' + rep.last_name;
							mySenators += '</a>';
							mySenators += '</p>';
						}
					});
					
					mySenators += '<p>Please write to them and let them know ...!</p>';
					
					$results.html(mySenators);
				
				} else {
					$results.html('<p>No senators found for zip code ' + zipcode + '. Please try again.</p>');
				}
			});
	});
});
</script>
</body>
</html>