csvデータからPHP・chart.jsで、日経平均株価のチャートを作ってみた

簡単すぎるぞ~

<?php

$data = file('nikkei225.csv', FILE_IGNORE_NEW_LINES);

unset($data&#91;0&#93;,$data&#91;-1&#93;);

function cut($item){
	return explode(',', $item);
}

$data = array_map("cut", $data);

foreach ($data as $value){
	$days&#91;&#93; = $value&#91;0&#93;;
	$high&#91;&#93; = $value&#91;3&#93;;
	$low&#91;&#93; = $value&#91;4&#93;;
}
/*
$php_day = json_encode($days);
$php_json = json_encode($low);*/
?>
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>
</head>

<body>
	<p><?php echo $php_json; ?></p>
  <canvas id="stage"></canvas>
</body>
<script type="text/javascript">
var array = <?php echo json_encode($days, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
console.log(array);
var array2 = <?php echo json_encode($high, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
console.log(array2);
var ctx = document.getElementById("stage");
var myLineChart = new Chart(ctx, {
  //グラフの種類
  type: 'line',
  //データの設定
  
  data: {
      //データ項目のラベル
      labels: array,
      //データセット
      datasets: [{
          //凡例
          label: "日経平均株価",
          //背景色
          backgroundColor: "rgba(75,192,192,0.4)",
          //枠線の色
          borderColor: "rgba(75,192,192,1)",
          //グラフのデータ
          data: array2
      }]
  },
  //オプションの設定
  options: {
      scales: {
          //縦軸の設定
          yAxes: [{
              ticks: {
                  //最小値を0にする
                  beginAtZero: true
              }
          }]
      }
  }
});
</script>
</html>

the Fetch Request

fetch('<URL-to-the-resource-that-is-being-requested>');
fetch('https://api.unsplash.com/search/photos?page=1&query=flowers')

fetch('https://api.unsplash.com/search/photos?page=1&query=${searchedForText}', {
	method: 'POST'
});

[javascriit]
fetch(‘https://api.unsplash.com/search/photos?page=1&query${searchedForText}’, {
headers: {
Authorization: ‘Client-ID abc123’
}
}).then(function(response){
debugger;
});[/javascript]

Since the Unsplash API we’re using will return JSON to us, we just need to call .json() on the response variable.

fetch('https://api.unsplash.com/search/photos?page=1&query${searchedForText}', {
	headers: {
		Authorization: 'Client-ID abc123'
	}	
}).then(function(response){
	return response.json();
});
function addImage(data){
	let htmlContent = '';
	const firstImage = data.result[0];

	if (firstImage){
		htmlContent = '<figure>
			<img src="${firstImage.urls.small}" alt="${searchedForText}">
			<figcaption>${searchedForText} by ${firstImage.user.name}</figcaption>
			</figure>
	} else {
		htmlContent = 'Unfortunately, no image was returned for your search.'
	}

	responseContainer.insertAdjacentHTML('afterbegin', htmlContent);
}

Handling returning error

const imgRequest = new XMLHttpRequest();
imgRequest.onload = addImage;
imgRequest.open('GET', 'https://api.unsplash.com/photos?page=1&query=${searchedForText}');
imgRequest.setRequestHeader('Authorization', 'Client-ID <client-id-here>');
imgRequest.send();
function addImage(){
	const data = JSON.parse(this.responseText);
	const firstImage = datat.results[0];

	responseContainer.insertAdjacementHTML('afterbegin', <figure>
		<img src="${firstImage.urls.small}" alt="${searchedForText}">
		<figcaption>${searchedForText} by ${firstImage.user.name}</figcaption>
		</figure>
		);
}

jQuery ajax()

$.ajax(<url-to-fetch>,<a-configuration-object>);
$.ajax(<just a configuration object>);

var settings = {
	frosting: 'buttercream',
	colors: ['orange', 'blue'],
	layers: 2,
	isRound: true
};

const myDeliciousCake = MakeCake({
	frosting: 'buttercream',
	colors: ['orange', 'blue'],
	layers: 2,
	isRound: true
});

$.ajax({
	url: 'http://swapi.co/api/people/1/'
});
function handleResponse(data){
	console.log('the ajax request has finished!');
	console.log(data);
}

$.ajax({
	url: 'http://swapi.co/api/people/1/'
}).done(handleResponse);

A request

function handleSuccess(){
	const data = JSON.parse(this.responseText);
	const.log(data);
}
asyncRequestObject.onload = handleSuccess;

unsplash for developer
https://unsplash.com/developers
create an application
https://unsplash.com/oauth/applications

The New York Times for developers
https://developer.nytimes.com/

function addImage(){}
const searchedForText = 'hippos';
const unsplashRequest = new XMLHttpRequest();

unsplashRequest.open('GET', 'https://api.unsplash.com/search/photos?page=1&query=${searchedForText}');
unsplashRequest.onload = addImage;

unsplashRequest.send()
function addArticles(){}
const articleRequest = new XMLHttpRequest();
articleRequest.onload = addArticles;
articleRequest.open('GET', 'http://api.nytimes.com/svc/search/v2/articlesearch.json?q=${searchedForText}&api-key=<API-key-goes-here>');
articleRequest.send();

APIs

What’s an API?
The acronym “API” stands for:

Application
Programming
Interface

google API
https://developers.google.com/apis-explorer/#p/
ProgrammableWeb
https://www.programmableweb.com/apis/directory

const asyncRequestObject = new XMLHttpRequest();
asyncRequestObject.open('GET', 'https://unsplash.com');
const req = new XMLHttpRequest();
undefined
req.open('GET', 'https://www.google.com/');
undefined
VM453:1 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
function handleSuccess(){
	console.log(this.responseText);
}
asyncRequestObject.onload = handleSuccess;

function handleError(){
	// in the function, the 'this' value is the XHR object
	console.log('An error occured');
}
asyncRequestOjbect.onerror = handleError;
function handleSuccess (){
	console.log(this.responseText);
}
function handleError(){
	console.log('An error occurred')
}

const asyncRequestObject = new XMLHttpRequest();

asyncRequestObject.open('GET', 'https://unsplash.com');
asyncRequestObject.onload = handleSuccess;
asyncRequestOjbect.onerror = handleError;

asyncRequestObject.send();

Ajax with XHR

GET Request: An internet request for data. Sent from a client to a server.
Response: A server’s response to a request. Sent from a server to a client. A response to a GET request will usually include data that the client needs to load the page’s content.

-Ajax Definition
Asynchronous
JavaScript
And
XML
request

Get request and response
Data: XML, JSON, HTML

xhr(XMLHttpRequest (XHR)) is Asynchronous

bower

sudo npm install -g bower

https://bower.io/

run bower install

var numLetters = function(letter){
	return new Function('times',
		"if (times < 0) return '';
		var result = '';
		times = Math.round(times);
		while(times--){ result += '" + letter +"'; }
		return result;"
		);
}
&#91;/javascript&#93;

&#91;javascript&#93;
<div id="beach-info"></div>
<script type="text/template" id="beach-supplies">
	<% if(supplies.empty) { %>
		<p> Whaaaat? Get to the beach anyway! </p>
	<% } %>

	<ul>
		<li> Sunscreen - <% if (supplies.sunscreen) { %> check! <% } %> </li>
		<% if (supplies.towel) { %>
			<li> Towel - Yes, a <%= supplies.towel =%> one! </li>
		<% } %>
		<li> Shades - <% if (supplies.shades) { %> check! <% } else { %> sadly, no!! <% } %></li>
	</ul>
</script>
var string = "Hi, my name is *(name)*. And I *(emotion)* this *(thing)*!";

var logResult = template( string );

logResult('Richard', 'love', 'green mint icecream', 2);

Yomen
npm install -g grunt-cli bower yo generator-karma generator-angular

click element

$('#my-elem').click(function(e){
	//the element has been clicked.. do stuff
})

document.body.innerHTML = ”;
document.body.style.background= “white”;

var num = [1, 2, 3];

for(var i = 0; i < nums.length; i++){ var num = nums[i]; var elem = document.createElement('div'); elem.textContent = num; elem.addEventListener('click', function(){ alert(num); }); document.body.appendChild(elem); } [/javascript] [javascript] getCurrentCat: function(){ return model.currentCat; }, getCats: function(){ return model.cats; }, setCurrentCat: function(cat){ model.currentCat = cat; }, incrementCounter: function(){ model.currentCat.clickCount++; catView.render(); } }; [/javascript]