Showing posts with label XHR. Show all posts
Showing posts with label XHR. Show all posts

Thursday 7 March 2019

Using the Vanilla JS Component template with LAMP

I use the Vanilla JS Component at https://github.com/guitarbeerchocolate/vanilla-js-component, and you have LAMP server on my box. However, when I want to call PHP scripts which are on the LAMP server such as, in a POST request using fetch or XHR within JavaScript I get the following errors in my browser:
Access to XMLHttpRequest at 'http://localhost/test/vanilla-js-POST-JSON/login.php' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

postjson_xhr.js:19 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost/test/vanilla-js-POST-JSON/login.php with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Obviously, it's treating the LAMP server like another domain.

The way to fix this is to put a line at the top of your PHP script thus:
header('Access-Control-Allow-Origin: *');
Happy coding.

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);
    }
  });
});