Tuesday 26 February 2019

Vanilla JavaScript Login form POST handler using XHR

I did a similar post to this called Vanilla JavaScript Login form POST handler using fetch. Fetch returns a JavaScript Promise, which can be a bit of a pain so I've also done a version using XHR, see below:

var postJSON = function(url, method, data, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
      callback(null, xhr.response);
    } else {
      callback(status, xhr.response);
    }
  };
  xhr.send(data);
};

Here's how to call it:
const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  postJSON(url, method, new FormData(form), function(error, json) {
    if (error !== null) {
      console.log('parsing failed', error);
    } else {
      console.log('json.username', json.username);
      console.log('json.password', json.password);
    }
  });
});

Tuesday 12 February 2019

Vanilla JS Bind

I have created a Vanilla JavaScript bind class. This has been built using https://github.com/guitarbeerchocolate/vanilla-js-component and resides at https://github.com/guitarbeerchocolate/JS_Bind
It employs :


  • HTML5
  • ES6

Vanilla JS carousel

I have created a Vanilla JavaScript carousel. This has been built using https://github.com/guitarbeerchocolate/vanilla-js-component and resides at https://github.com/guitarbeerchocolate/vanilla-js-carousel
It employs :

  • HTML5
  • SASS
  • BEM
  • ES6

Vanilla JS component

I'm creating a number of elements using Vanilla JavaScript. They will use :

  • HTML5
  • SASS
  • CSS grid
  • BEM
  • Media queries
  • ES6

In order to put these elements together more efficiently, I have put together a small framework, from which I will fork.
It lies at https://github.com/guitarbeerchocolate/vanilla-js-component

Wednesday 6 February 2019

Vanilla JavaScript Login form POST handler using fetch

I've been updating my gists lately because I'm now in position to leave jQuery behind. See https://gist.github.com/guitarbeerchocolate
So, here's how to pass login form data to some middleware and accept JSON in return using fetch.

const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  fetch(url, {
    method: method,
    body: new FormData(form)
  }).then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('json.username', json.username)
    console.log('json.password', json.password)
  }).catch(function(error) {
    console.log('parsing failed', error)
  })
});