W: H: YOffset??
Related Media
Categories   /  Tags

Javascript, ECMAScript-6 snippets

Examples in pure Javascript, Vanilla, ES6 with a focus on asynchronous HTTP requests using fetch and user interface effects.

Fetch API examples & JSON

Post and get object data using fetch and php file. 
Returns single string or an object array from php and refreshs every 30 seconds.

 

function fetchDate() {
	let str = document.querySelector("#theTime");
	let user = {
		"username" : "Denis",
		"location" : "Berlin",
		"street" : "my Street"
	}
		fetch("./data.php", {
			"method": "POST",
			"headers": {
				"Content-Type" : "application/json; charset:utf-8"
			},
			
			"body" : JSON.stringify(user)
		}).then(function(response){
			
			return response.text();
			//return response.json();
		}).then(function(data){
			console.log(data)
			str.innerHTML = (data);
			//console.log(data['location'])
			//str.innerHTML = (data['location']);
		})
		
	}
window.addEventListener("load", () => {
	var fetchInterval = 30000; // 30 seconds.
	setInterval(fetchDate, fetchInterval);

 

The associated php file:
data.php

 

<?php
if(isset($_POST)) {
$data = file_get_contents("php://input");
//  $data = date("H:i", time());
$user = json_decode($data,true);
echo $user["username"];
}
?>

 

// To get and output the full object array, change this line in javascript to JSON format.
// return response.text(); return response.json();

 

The associated php file:
data.php

 

<?php
// returns the full object
if(isset($_POST)) {
$data = file_get_contents("php://input");
$user = json_decode($data,true);
echo json_encode($user);
}
?>