Interactive slides + runnable examples (AJAX, Axios, Fetch)
Content-Type, auth tokensJSON.stringify() to convert object β JSON stringJSON.parse() to convert JSON string β objectClassic approach (often taught with jQuery): asynchronous requests, update parts of page.
Promise-based client with simpler syntax + automatic JSON parsing.
Built-in browser API; modern, lightweight, very common.
https://jsonplaceholder.typicode.com. You need an internet connection to see real responses.
$.ajax({})url β Required: endpoint URLmethod β Default GET (GET, POST, PUT, DELETE)data β Data to send in POST/PUT requestscontentType β Use "application/json" for JSONsuccess β callback for successerror β callback for errorJSON.stringify(...) for the request body (especially with jQuery / Fetch).
GET request to /usersusers.forEach(function(u){ ... }) and append like:
$("#pp1-users").append("<li>" + u.name + "</li>")
contentType: "application/json"data: JSON.stringify({...})/postsid from the created postxhr.status){ title: "Practice Post", body: "Hello from HCDD 411", userId: 1 }
.then() and .catch()?success / error.then(...) = βwhen it succeeds, do thisβ.catch(...) = βif it fails, do thisβaxios.get(...) works immediatelynpm i axiosconst axios = require("axios")node app.jsresponse.dataaxios.get(url) β returns a Promise.then(...) (or await)response.datasuccess/error)get/post/put/delete) and handle a Promise (.then/.catch)JSON.stringify(data)response.dataerror: function(err){...}.catch(err => ...)fetch(url) returns a Promise that resolves to a Responseresponse.json() (this is also async)response.ok and throw an error yourselfasync / await: How to use it (Step-by-step)async makes a function return a Promiseawait pauses inside that async function until the Promise resolvestry/catch to handle errors like a normal synchronous programawait something() β something().then(...) (same idea, easier to read)await only works inside an async function (in this lecture style)await outside an async function (or outside an ES module).
.then() to handle success.catch() to handle errors.then((response) => response.json())const data = await response.json()async function getUserEmail(id)fetch, check response.ok, then await response.json()email/postsuserId === 1posts.filter(...).slice(0, 5).forEach(...)