Skip to content

Instantly share code, notes, and snippets.

@zcaceres
Created March 22, 2017 20:56
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 zcaceres/4c829241ad973daa9eebe3c73787427f to your computer and use it in GitHub Desktop.
Save zcaceres/4c829241ad973daa9eebe3c73787427f to your computer and use it in GitHub Desktop.
AJAX – FSA 1702 – March 22, 2017

AJAX – Let's Get A-Jacked!

FSA 1702 – March 22, 2017

AJAX helps us make requests from the client-side.


Old HTTP Requests

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>.

AJAX

  • Make background HTTP requests with JS.
  • Handling response of HTTP requests with JS
  • No page refresh necessary

A brief history...

  • 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.

What's up with XML?

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!

Defer and Async Tags

<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.

Using AJAX

// 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.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment