FSA 1702 – March 22, 2017
AJAX helps us make requests from the client-side.
Each time we do a URL bar query we re-render the HTML completely. The same is true with a POST request using a form.
AJAX allows us to move HTTP requests to the background and replace only part of the DOM.
Currently our background requests occur only in <script>
or <link>
.
- Make background HTTP requests with JS.
- Handling response of HTTP requests with JS
- No page refresh necessary
-
1996 - 2002: Microsoft Invents
<iframe>
then awkwardly implements it with ActiveX. -
2002: Google makes a huge step by implementing XMLHttpRequest in Gmail and Google Maps. WHOA. Popularized. Kayak.com also uses it.
-
2005: Named AJAX for asynchronous Javascript and XML.
-
TODAY: We live in an era of single-page apps that rarely refresh and leverage AJAX massively!
$.ajax() returns a promise
Ajax does not depend on jQuery – but using jQuery is helpful.
A data serialization format (how we format the data when we send it across).
Examples of Data serialization formats: JSON, XML, YAML.
XML is used for delivery of data over limited transports like HTTP.
It looks a lot like HTML.
JSON is more frequently used today than XML. But AJAJ just doesn't sound so nice!
<script defer src="/myscript">
// ^ will wait till DOM is loaded before getting this script
</script>
The async
tag downloads now and then runs once it's downloaded.
The defer
tag downloads now and runs only after the DOM is finished parsing.
// Client Front-End
const allList = $('#all-hats');
const kindInput = $('[name="kind"]');
const colorInput = $('[name="color"]')
const brimInput = $('[name="brim"]')
const weightInput = $('[name="weight"]')
$('#add-hat-submit').on('submit', function() {
$.ajax({
method: 'POST',
url: '/api/hats',
data: {
kind: kindInput.val(),
color: colorInput.val(),
brim: brimInput.val() == 'on',
weight: weightInput.val(),
}
}).then(function(response) {
// This will add new content to our page without refreshing. Amazing!
const newElement = $(`<li style="color: ${response.color}">${response.kind}</li>`);
allHatsList.append(newElement);
console.log(response);
}).catch(function(err) {
console.err(err);
});
});
// For this query to work we need to have a route that handles the Sequelize.findAll().. see below
$.ajax({
method:'GET',
url: '/api/hats'
}).then (function (hats) {
hats.forEach(function(hat) {
const newElement = $(`<li style="color: ${response.color}">${response.kind}</li>`);
allHatsList.append(newElement);
})
})
//Server Back-end
app.post('/api/hats', function (req,res,next) {
Hat.create(req.body)
.then(function(createdHat) {
res.status(201).json(createdHat);
}).catch (function(err) {
next(err);
})
})
app.get('/api/hats', function (req,res,next) {
Hat.findAll()
.then(function(theHats) {
res.json(theHats);
}).catch(function(err) {
next(err);
})
})
The Network Tab is your friend.