· 6 years ago · Sep 01, 2019, 07:22 PM
1How does the web work?
2
3
4
5
6
7
8
9
101 HTTP request / file (file.html, file.css, file.js, file.png)
11
12HTTP
13Base protocol of the Web (!= Internet)
14
15**H**yper**T**ext**T**ransfer**P**rotocol
16
17What is it?
18A protocol to transfer resources
19
20Resource means file (HTML, CSS, images, JS, ...)
21
22Based on a system of request / response
23
24Between 2 machines, a client and a server
25
26curl
27curl -i http://perdu.com
28To see the whole client / server communication:
29
30curl -i -v http://perdu.com
31Let's look at an HTTP request
32It's more than just a URL
33
341 - Verb
35GET: **R**ead
36
37POST: **C**reate
38
39PATCH: **U**pdate
40
41DELETE: **D**elete
42
43
44
45
46REST pattern
47
482 - URL
49https://www.google.com/search?q=wagon&hl=en
50
51
52
53Scheme: https
54Host: www.google.com
55Path: /search
56Query String: q=wagon&hl=en
573 - Headers
58
59
604 - Body
61No body for a GET Request
62Body for a POST or PATCH request (usually with content from form)
63GET
64
65
66POST
67
68
69AJAX
70Asynchronous Javascript And XML
71
72AJAX requests are asynchronous HTTP requests which happen after page load.
73
74Example: Google search (autocomplete)
75
76
77
78How?
79Old school way: use [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest)
80
81Easier way: Fetch
82fetch on MDN
83
84// GET request
85fetch(url).then((response) => {
86 // Do something once HTTP response is received
87});
88GET requests
89Fetching JSON
90Let's use the OMDb API
91
92fetch("http://www.omdbapi.com/?s=harry potter&apikey=adf1f2d7")
93 .then(response => response.json())
94 .then((data) => {
95 console.log(data);
96 });
97API Key
98Pick an API key:
99
100adf1f2d7
10148727053
1028691812a
103Using JSON data
104<ul id="results"></ul>
105const results = document.querySelector("#results");
106
107fetch("http://www.omdbapi.com/?s=harry potter&apikey=adf1f2d7")
108 .then(response => response.json())
109 .then((data) => {
110 data.Search.forEach((result) => {
111 const movie = `<li class="list-inline-item">
112 <img src="${result.Poster}" alt="">
113 <p>${result.Title}</p>
114 </li>`;
115 results.insertAdjacentHTML("beforeend", movie);
116 });
117 });
118Adding style
119<!-- head -->
120<link rel="stylesheet"
121 href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
122<!-- body -->
123<div class="container text-center">
124 <ul id="results" class="list-inline"></ul>
125</div>
126Let's add a search form!
127
128Combine with events (1)
129<form id="search-movies" class="form-inline">
130 <input id="keyword" type="text" class="form-control ml-auto mr-2" placeholder="Find movies">
131 <input type="submit" class="btn btn-primary mr-auto ml-2" value="Search">
132</form>
133const searchMovies = (query) => {
134 fetch(`http://www.omdbapi.com/?s=${query}&apikey=adf1f2d7`)
135 .then(response => response.json())
136 .then((data) => {
137 data.Search.forEach((result) => {
138 const movie = `<li class="list-inline-item">
139 <img src="${result.Poster}" alt="">
140 <p>${result.Title}</p>
141 </li>`;
142 results.insertAdjacentHTML("beforeend", movie);
143 });
144 });
145};
146Combine with events (2)
147// [...]
148const form = document.querySelector('#search-movies');
149
150form.addEventListener('submit', (event) => {
151 event.preventDefault(); // <-- to prevent <form>'s native behaviour
152 const input = event.currentTarget.querySelector('.form-control');
153 results.innerHTML = '';
154 searchMovies(input.value);
155});
156Full solution
157
158POST requests
159POST request with fetch
160Let's live-code a reverse engineering of the Algolia Places API endpoint.
161
162const searchAlgoliaPlaces = (event) => {
163 fetch("https://places-dsn.algolia.net/1/places/query", {
164 method: "POST",
165 body: JSON.stringify({ query: event.currentTarget.value })
166 })
167 .then(response => response.json())
168 .then((data) => {
169 console.log(data.hits); // Look at local_names.default
170 });
171};
172
173const input = document.querySelector("#search");
174input.addEventListener("keyup", searchAlgoliaPlaces);
175Happy Ajaxing!