Skip to content

Instantly share code, notes, and snippets.

@jordangarcia
Created June 28, 2019 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordangarcia/6f936813a54eec4b0657d517cdf67ad1 to your computer and use it in GitHub Desktop.
Save jordangarcia/6f936813a54eec4b0657d517cdf67ad1 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Horizons AJAX Async Example</title>
</head>
<body>
<h1>AJAX Async Example</h1>
<p>Use <a href="http://api.jquery.com/jquery.ajax/">$.ajax()</a> to fetch <a href="https://horizons-school-of-technology.github.io/week02/day4/examples/products.json">these products</a> in JavaScript on this page. Display their names and prices below as a bulleted list.</p>
<p>
The link above will respond with an array of urls. You need to asynchronously make AJAX requests to these links, and then sort the results in increasing price order (lowest price up top).
</p>
<div id="products">REPLACE me with the sorted list of products! My <code>id is "products"</code>.</div>
<h2>Example output</h2>
<ul>
<li>Raspberry Pi, $33.53</li>
<li>Amazon Echo, $179.99</li>
<li>DJI Phantom 3, $416.59</li>
</ul>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="async.js"></script>
<script>
// YOUR CODE HERE
</script>
</body>
</html>
// prettier-ignore
const PRODUCTS_URL = "https://horizons-school-of-technology.github.io/week02/day4/examples/products.json";
function getAllProductDetails(productUrls, callback) {
let products = [];
for (let i = 0; i < productUrls.length; i++) {
let url = productUrls[i].url;
$.ajax(url, {
success: function(productDetail) {
products.push(productDetail);
if (products.length === productUrls.length) {
callback(products);
}
}
});
}
}
function formatPriceInCents(number) {
return `$${String(number / 100)}`;
}
function insertProducts(products) {
products.sort(function(a, b) {
return a.priceCents - b.priceCents;
});
const ul = $("<ul>");
products.forEach(product => {
ul.append(
$(`<li>${product.name}, ${formatPriceInCents(product.priceCents)}</li>`)
);
});
$("#products")
.empty()
.append(ul);
}
$.ajax(PRODUCTS_URL, {
success: function(productUrls) {
getAllProductDetails(productUrls, function(products) {
insertProducts(products);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment