Car JS API
jquery and javascript classes
%%html
<head>
<!-- load jQuery and DataTables scripts -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>var define = null;</script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
</head>
<table id="table" class="table" style="width:100%">
<thead id="head">
<tr>
<th>Car ID</th>
<th>Make ID</th>
<th>Make Name</th>
</tr>
</thead>
<tbody id="body"></tbody>
</table>
<script>
function uniqueID() {
if ( typeof uniqueID.counter == 'undefined' ) {
uniqueID.counter = 0;
}
uniqueID.counter++;
return uniqueID.counter;
}
class Car {
constructor(makeID, make) {
this._id = uniqueID();
this.makeID = makeID;
this.make = make;
}
getId() {
return this._id;
}
}
$(document).ready(function() {
const options = {
method: 'GET',
async: true,
crossDomain: true,
};
// fetch the API
fetch("https://vpic.nhtsa.dot.gov/api/vehicles/getallmakes?format=json", options)
.then(response => {
if (!response.ok) {
throw new Error('API response failed');
}
return response.json();
})
.then(data => {
for (const row of data["Results"]) {
var car = new Car(row["Make_ID"], row["Make_Name"]);
$('#body').append('<tr><td>' +
car.getId() + '</td><td>' +
row["Make_ID"] + '</td><td>' +
row["Make_Name"] + '</td></tr>');
}
$("#table").DataTable();
})
.catch(error => {
console.error('Error:', error);
});
});
</script>