Chapter 9 · Core
Talking to servers
Most real websites load and save data while you use them: new messages appear, a "Like" is saved, search results show up as you type, all without the page reloading. In this chapter you'll learn how to load data from a server, send data to it, upload files, and handle things going wrong.
What is a server, and what is AJAX?
A server is a computer somewhere on the internet that stores a website's data: the students, the messages, the marks. Your page runs in the visitor's browser, so it has to ask the server whenever it needs that data, a bit like a customer asking a waiter:
Asking the server without reloading the page has a name: AJAX. With Nyx, each kind of request is one short line.
Data in JSON
Servers usually send data in a format called JSON. It looks like this:
[
{ "name": "Ananya Ghosh", "city": "Howrah", "marks": 92 },
{ "name": "Rahul Kumar", "city": "Kolkata", "marks": 81 }
]Nyx turns JSON into normal JavaScript for you. Two shapes appear all the time:
list.length tells you how many items there are, and list[0] is the first one.student.name gives "Ananya Ghosh", and student.marks gives 92.To do something with every item in a list, use .forEach():
Watch the Output below.
.forEach() runs the function once for each item, just like Nyx's .each() from Finding elements.
Waiting for the answer: await
A server takes a moment to answer, but JavaScript doesn't stop and wait unless you tell it to. Without waiting, you'd get an empty promise instead of the data. The word await means "wait here until the answer arrives":
Without await
const students = nyx.get("examples/students.json");
print(students);Prints "a Promise": the answer hasn't arrived yet.
With await
const students = await nyx.get("examples/students.json");
print(students);Waits, then prints the real list.
On your own pages: async
You can only use await inside a function marked async. The examples on this site take care of that for you, but on your own pages, add async in front of the function:
// When the page is ready
nyx(async () => {
const students = await nyx.get("/api/students");
});
// When a button is clicked
nyx("#load").on("click", async (event, button) => {
const students = await nyx.get("/api/students");
});Browsers block these requests on pages opened by double-clicking the file (the address starts with file://). To try AJAX on your own computer, run a small local server: in VS Code, install the Live Server extension and click Go Live. Websites on the internet are already on a server, so they work as they are.
Loading data
nyx.get() asks a server, or a file, for data. This site has a real file of students at examples/students.json. Let's load it and show it on the page:
- Not loaded yet
await nyx.get("examples/students.json")Ask for the file and wait for it. Nyx turns the JSON into a list.nyx("#x-roster").empty();Remove the "Not loaded yet" line.students.forEach(...)For each student, build a list item safely withnyx.create()and add it.
Asking a question: parameters
Give nyx.get() a second value to add details to your request, like a search word. Nyx adds them to the address for you:
nyx.get("/api/students", { city: "Kolkata", page: 2 });
// asks for: /api/students?city=Kolkata&page=2The practice server
Loading a file is easy, but saving data needs a real server program, which this website doesn't have. So, for practice, this page has a small pretend server built in. Any address that starts with demo-api/ is answered by it, after a short pause, just like a real one:
GET demo-api/messagesGives you the list of messages.POST demo-api/messagesSaves a new message. Send { name, text }. An empty text is refused.PUT demo-api/messages/1Changes message number 1.DELETE demo-api/messages/1Deletes message number 1.GET demo-api/studentsThe students. Add { q: "kol" } to search by name or city.POST demo-api/uploadPretends to save a file, and tells you its name and size.POST demo-api/signupPretends to register someone. The email asha@school.in is already taken, so you can practise showing the server's answer.GET demo-api/slowTakes 3 seconds to answer.GET demo-api/brokenAlways fails, so you can practise handling errors.The practice server only exists on this website, and it forgets everything when you reload the page. On your own site, the addresses will point to your real server, for example a PHP file or WordPress (see WordPress). The Nyx code stays exactly the same.
Sending data
Requests come in different kinds, called methods. Each one tells the server what you want to do:
nyx.get(url)Give me something. Changes nothing on the server.nyx.post(url, data)Save something new, like a new message or a sign-up.nyx.put(url, data)Replace something that already exists.nyx.patch(url, data)Change part of something, like marking a message as read.nyx.delete(url)Delete something.Give the data as an object in curly brackets. Nyx sends it as JSON and gives you the server's answer:
Nothing sent yet.
The server answers with the saved message, including the id number it gave it. Run it a few times and the number goes up.
Watch the Output below.
Message 1 is changed and message 2 is deleted. If message 2 doesn't exist yet, run the example above first, or read Nyx's explanation in the Output.
Sending a form
A form already says where it should go (action) and how (method). .send() sends all its fields there, without reloading the page:
async (event, form) =>async, because we useawaitinside.await form.send()Send every field (nameandtext) to the form'saction, using itsmethod, and wait for the answer.form.reset();Put the fields back to how they started.
Press Run, type a message and press Send. Then try sending an empty message and read the Output.
To get a form's values as an object, without sending them, use .formData(): form.formData() gives { name: "Ravi", text: "..." }.
Uploading files
In Changing content, you read a file from a file box. To send it to a server, put it in a form and send the form. Nyx sends files the way servers expect them.
Press Run, choose any file, then press Upload. The practice server doesn't keep the file; it only reports what it received.
You can also send a file without a form, using FormData, the browser's own "envelope" for files:
const data = new FormData();
data.append("homework", nyx("#file").value()); // the chosen file
data.append("student", "Asha");
await nyx.post("/api/upload", data);Loading HTML into the page
.load() fetches another HTML file and puts it inside an element. Add a selector after the address to take just one part of that file:
nyx("#news").load("news.html"); // the whole file
nyx("#news").load("news.html #latest"); // only the #latest partThe file examples/notice.html also has a header and a footer, but only the #notice part was put on the page.
When it goes wrong
Requests can fail: the internet drops, an address is misspelt, the server has a bug. When that happens, Nyx explains the problem in plain English in the console, and the line with await throws an error, which stops your code. To handle it yourself, use try and catch:
try {
// the code that might fail
} catch (error) {
// what to do if it fails
}…
The error Nyx gives you has these details:
error.messageWhat went wrong, written for people. Safe to show to visitors.error.hintHow to fix it. This one is for you, the developer.error.statusThe server's answer code, like 404. It's 0 if the server couldn't be reached at all.error.dataWhatever the server sent back with the error, if anything.Common status codes
200OK. Everything worked. (Nyx doesn't treat this as an error.)201Created. Something new was saved.400The server didn't accept what you sent.401You need to log in first.403You're not allowed to do this.404Nothing at that address. Check the spelling.422The data was the wrong shape, like an empty required field.429Too many requests too quickly.500The server has a bug. It's not your JavaScript's fault.Try a misspelt address and an empty message, and read what Nyx says in the Output:
Watch the Output below.
Showing that it's working
If nothing happens after a click, visitors click again. .busy() switches a button off and shows "Loading…" until the request has finished, then puts it back:
button.busy(request, "Loading results…")Give it the request and, if you like, your own text. Without text, it shows "Loading…".awaitWaits for the request, just as before, and gives you its answer.
Options
Every request can take one more value: an object of options. For nyx.get() it comes after the parameters; use null if you have no parameters.
nyx.get("/api/students", null, { timeout: "10 seconds", retry: 2 });
nyx.post("/api/messages", data, { timeout: "10 seconds" });timeout: "10 seconds"Give up if there's no answer in this time. Normally 30 seconds.retry: 2If the connection drops or the server fails, try again up to 2 more times.cache: "5 minutes"Remember the answer and reuse it for this long instead of asking again. Only for nyx.get().latest: "search"Ignore older requests with the same name when a newer one starts. See the search example below.headers: { ... }Extra information sent with the request, like an API key.as: "text"Give back plain text instead of turning JSON into objects.as: "form"Send the data the way an HTML form would, instead of as JSON. Some older servers need this.quiet: trueDon't write the error in the console. Useful when you handle it yourself.full: trueGive back { data, status, headers } instead of just the data.To set an option for every request at once, change nyx.defaults, for example nyx.defaults.timeout = "10 seconds";. To forget everything remembered with cache, call nyx.clearCache().
Search as you type
Searching on every key press sends lots of requests, and a slow, older answer can arrive after a newer one and show the wrong results. Two tools fix this together: nyx.debounce() waits until the visitor stops typing, and latest ignores any older answer.
Press Run, then type kol or priya. You'll learn more about nyx.debounce() in Time.
Putting it together
A small class message board. It loads the messages, sends new ones, shows that it's busy, and explains problems kindly.
async function showMessages() { ... }A named function that loads the messages and draws the list. We use it at the start and after every post..busy(nyx.post(...))Send the message while the Post button shows "Loading…".{ quiet: true }We show the problem on the page ourselves, so Nyx doesn't need to write it in the console too.catch (error) { ... }If posting fails, for example an empty message, show the reason and put the cursor back in the box.await showMessages();Load the messages once, as soon as the code runs.
Common mistakes
await: const data = await nyx.get(url);async to the function around it: async () => { ... }.file://. Use a local server, like VS Code's Live Server.try { ... } catch (error) { ... } and show error.message.nyx.get() to load and nyx.post() to save. If a server says 405, you used the wrong one.Exercise
Fill in the blanks, then press Check answers.
1. Load the posts and wait for them.
const posts = nyx.get("/api/posts");
2. Save a new message on the server.
await nyx.("/api/messages", { text: "Hi" });
3. Delete message number 5.
await nyx.("/api/messages/5");
4. Send the form #signup to its own action.
await nyx("#signup").();
5. Handle a failed request.
try {
await nyx.get("/api/posts");
} (error) {
nyx.toast(error.message);
}
6. A click listener that uses await inside.
nyx("#load").on("click", () => {
await nyx.get("/api/posts");
});
Remember
await waits for the answer. It only works inside an async function.nyx.get() loads. nyx.post(), put(), patch() and delete() change things.form.send() sends a whole form, files included. .load() puts HTML from another file on the page.try / catch and show error.message..busy() stops double clicks. latest and nyx.debounce() make search-as-you-type reliable.file://.