Skip to content

Instantly share code, notes, and snippets.

@shgysk8zer0
Last active August 29, 2015 14:22
Show Gist options
  • Save shgysk8zer0/a15e4462521192f3d691 to your computer and use it in GitHub Desktop.
Save shgysk8zer0/a15e4462521192f3d691 to your computer and use it in GitHub Desktop.
Example of using the new Headers, URL, FormData, & Request APIs along with fetch as a Promise
function submitForm(form) {
if (! ('fetch' in window)) {
return new Promise(function() {
throw new Error('Your browser does not support the fetch API');
});
}
var url = new URL(form.action || '/', document.baseURI || location.origin);
var headers = new Headers();
var body = new FormData(form);
headers.append('Content-Type', form.enctype || 'multipart/form-data');
headers.append('Accept', 'application/json');
body.append('form-name', form.name);
var request = new Request(url, {
headers: headers,
method: form.method || 'POST',
body: body
});
return fetch(request);
}
function checkNotificationPermission(parent) {
if ('Notification' in window && Notification.permission === 'default') {
if (typeof parent === 'undefiend') {
parent = document.body;
} else if (typeof parent === 'string') {
parent = document.querySelector(parent);
}
var button = document.createElement('button');
var container = document.createElement('div');
container.appendChild(button);
button.type = 'button';
button.textContent = 'Allow Notifications';
parent.insertBefore(container, parent.firstElementChild);
button.addEventListener('click', function(event) {
Notification.requestPermission(function() {
if (Notification.permission === 'granted') {
event.target.parentElement.parentElement.removeChild(event.target.parentElement);
};
});
});
}
}
window.addEventListener('load', function() {
'use strict';
checkNotificationPermission(document.body);
document.querySelector('form').addEventListener('submit', function(event)
{
event.preventDefault();
submitForm(event.target).then(function(resp) {
if (resp.ok) {
return resp;
} else {
throw new Error('Request got a response status code of ' + resp.statusText);
}
}).then(function(resp) {
switch(resp.headers.get('Content-Type')) {
case 'application/json':
return resp.json();
case 'application/xml':
return resp.text().then(function(xml) {
return new DOMParser().parseFromString(xml, 'application/xml');
});
case 'text/html':
case 'text/html; charset=utf-8':
return resp.text().then(function(html) {
return new DOMParser().parseFromString(html, 'text/html');
});
default:
throw new Error('Unhandled Content-Type: ' + resp.headers.get('Content-Type'));
}
}).then(function(resp) {
if ('notify' in resp) {
new Notification(resp.notify.title, resp.notify.init);
}
if ('log' in resp) {
console.log(resp.log);
}
}).catch (function (err) {
if (err instanceof Error) {
new Notification('An error occured', {body: err.message});
}
console.error(err);
});
});
});
<?php
if (getallheaders()['Accept'] === 'application/json') {
$data = array(
'notify' => array(
'title' => 'Form Submitted',
'init' => array(
'body' => 'Check your browser\'s console for results',
'icon' => 'data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjEwMjQiIHdpZHRoPSIxMDI0IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxwYXRoIGQ9Ik04MzIgMzJjLTEzMCAwLTEyNCAxMzAtNzA0IDEyOEM1Ny4zNDQgMTYwIDAgMjc0LjYyNSAwIDQxNnM1Ny4zNDQgMjU2IDEyOCAyNTZjMjIuNzgxIDAgNDMuMTg4IDAuNSA2NC4xODggMC44NzVMMjU2IDk2MGwxOTIgMzIgNjQtOTYtNDUuMTI1LTIwMy4xMjVDNzA5LjM3NSA3MjkuMTI1IDczMy43NSA4MDAgODMyIDgwMGMxMDYgMCAxOTItMTcyIDE5Mi0zODRDMTAyNCAyMDMuOTY5MDAwMDAwMDAwMDUgOTM4IDMyIDgzMiAzMnpNMTk3IDQ4Mi45MzhjLTM5LjE4OC0xLjQ2OS04Mi4xODgtMi4yNS0xMjcuNTYyLTIuNjI1QzY2IDQ2MC41OTQgNjQgNDM4LjkwNiA2NCA0MTZjMC04OC4zNzUgMjguNjg4LTE5MiA2NC0xOTIgMzkuMDMxIDAuMTI1IDc1LTAuNDM4IDEwOS0xLjQwNkMyMDkuNjU2IDI2OS41NjIgMTkyIDMzOC4zMTIgMTkyIDQxNiAxOTIgNDM5LjMxMiAxOTQuMDYyIDQ2MS40MzggMTk3IDQ4Mi45Mzh6TTI2MS4zMTIgNDg1LjkzOEMyNTguMTI1IDQ2My42ODggMjU2IDQ0MC4zNzUgMjU2IDQxNmMwLTc5LjUgMTguNDM4LTE0OS41IDQ2LjkwNi0xOTYuMjE5IDE1NS4xNTYtOC4zMTIgMjUxLjkwNi0yOC40NjkgMzE5LjAzMS01MC4xODhDNTkzLjYyNSAyMzYuNDY5MDAwMDAwMDAwMDUgNTc2IDMyMS42NTYgNTc2IDQxNmMwIDQwIDMuODc1IDc4IDkuNSAxMTQuMzEyQzUxMy4zNDQgNTExLjYyNSA0MTIuODEyIDQ5NC41OTQgMjYxLjMxMiA0ODUuOTM4ek04MzIgNzA0Yy0xMi4xMjUgMC0yMy42ODgtNS4wNjItMzQuODEyLTEyLjEyNS0xNS4yNS02Ny4zMTItODMuNDM4LTQxOC4zNDQgMTE3LjQzOC00OTQuMTg4Qzk0Mi4xMjUgMjUwLjUgOTYwIDMyOC4xODggOTYwIDQxNiA5NjAgNTc1IDkwMi42MjUgNzA0IDgzMiA3MDR6IiAvPgo8L3N2Zz4K'
)
),
'log' => $_REQUEST
);
$json = json_encode($data);
header('Content-Type: application/json');
exit($json);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example of using the new Headers, URL, FormData, &apm; Request APIs</title>
<script type="application/javascript">
if (! ('fetch' in window)) {
document.write('\<script type="application/javascript" src="https://raw.githubusercontent.com/github/fetch/master/fetch.js"\>\</script\>');
}
</script>
<script type="application/javascript" src="fetch_sample.js" async></script>
<link rel="stylesheet" media="screen" href="style.css">
<link rel="icon" sizes="any" href="data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjEwMjQiIHdpZHRoPSI4OTYiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPHBhdGggZD0iTTYwOCAxOTJsLTk2IDk2IDIyNCAyMjRMNTEyIDczNmw5NiA5NiAyODgtMzIwTDYwOCAxOTJ6TTI4OCAxOTJMMCA1MTJsMjg4IDMyMCA5Ni05NkwxNjAgNTEybDIyNC0yMjRMMjg4IDE5MnoiIC8+Cjwvc3ZnPgo=">
</head>
<body>
<form name="login" action="<?=$_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
<fielset form="login">
<legend>Login Form</legend>
<hr>
<div>
<label for="user" title="email address"></label>
<input type="email" name="user" id="user" placeholder="user@example.com" autofocus required>
</div>
<div>
<label for="password" title="password"></label>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</div>
</fieldset>
</form>
</body>
</html>
:root {
font-size: 18px;
}
form {
display: inline-block;
padding: 1em;
border: 2px double dimgray;
box-shadow: 0.5em 0.5em 1em black;
background-image: linear-gradient(gainsboro, whitesmoke);
background-color: red;
}
label::before {
content: '';
display: inline-block;
width: 1rem;
height: 1rem;
margin: 0 0.5em 0 0.3em;
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
label[for="user"]::before {
background-image: url('data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjEwMjQiIHdpZHRoPSI4OTYiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPHBhdGggZD0iTTAgMTkydjY0MGg4OTZWMTkySDB6TTc2OCAyNTZMNDQ4IDUyMCAxMjggMjU2SDc2OHpNNjQgMzIwbDI1Mi4wMzEgMTkxLjYyNUw2NCA3MDRWMzIwek0xMjggNzY4bDI1NC0yMDYuMjVMNDQ4IDYxMmw2NS44NzUtNTAuMTI1TDc2OCA3NjhIMTI4ek04MzIgNzA0TDU3OS42MjUgNTExLjkzOCA4MzIgMzIwVjcwNHoiIC8+Cjwvc3ZnPgo=');
}
label[for=password]::before {
background-image: url('data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjEwMjQiIHdpZHRoPSI3NjgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPHBhdGggZD0iTTcwNCA0NDhjLTMyIDAtNjQgMC02NCAwczAtNjQgMC0xOTItMTI4LTI1Ni0yNTYtMjU2LTI1NiAxMjgtMjU2IDI1NiAwIDE5MiAwIDE5Mi0zMiAwLTY0IDAtNjQgMzItNjQgNjQgMCA0MTYgMCA0NDggMzIgNjQgNjQgNjQgNjA4IDAgNjQwIDAgNjQtMzIgNjQtNjQgMC00MTYgMC00NDgtMzItNjQtNjQtNjR6IG0tMTkyIDEyOGgtMzg0djY0aDM4NHY2NGgtMzg0djY0aDM4NHY2NGgtMzg0djY0aDM4NHY2NGgtNDQ4di00NDhoNDQ4djY0eiBtMC0xMjhoLTI1NnMwLTEyOCAwLTE5MiA2NC0xMjggMTI4LTEyOCAxMjggNjQgMTI4IDEyOCAwIDE5MiAwIDE5MnoiIC8+Cjwvc3ZnPgo=');
}
input {
margin-right: 3em;
border-width: 0 0 2px 0;
border-color: black;
margin-top: .8em;
background-color: transparent;
}
form button {
color: whitesmoke;
border: 0;
border-radius: 1em;
cursor: pointer;
}
button[type=submit] {
background-image: linear-gradient(green, darkgreen, green);
}
button[type=submit]:hover {
background-image: linear-gradient(lightgreen, green, lightgreen);
}
button[type=reset] {
background-image: linear-gradient(red, darkred, red);
}
button[type=reset]:hover {
background-image: linear-gradient(red, red, red);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment