In this article I'd like to share with you 2 simple templates that will help you grab data from servers
They are copy-paste ready-to-use templates. Some changes need to be done depending on how you want to use received data. In my examples I explain basic principles of retrieving data from servers just logging it to a console. Everything is explained with simple terms and words.
All data is stored on servers in JSON format. They are always objects consisting of strings.
The URL with JSON data that I'm using for my examples is: https://jsonplaceholder.typicode.com/users
AJAX / XMLHttpRequest
This code sends a GET request to a server. It means that we just receive some data from a server without sending anything back and not modifying any data stored on a server
Inside the function on lines 4-9 we write everything that we want to do with the data that we receive from a server.
After that we use map() method and a callback function passed in inside map() to iterate over each object inside an array stored in a 'res' variable and grab data that we need.
The callback function in our case is an arrow function. It's parameter 'item' represents each individual object.
As we could see in the picture above each object has multiple keys ('address', 'company', 'email', etc). By appending key names to our parameter 'item' we are able to access corresponding values.
In our example on line 7 we access the key 'name' and log its values from all the objects to a console (item => console.log(item.name)). The result will be the names from all the object logged to a console one after the other.
When we send a request to a server using fetch() method we receive a JSON object and save it in a variable 'res'. You can give a variable any name you like. Make sure that you don't put semicolon after fetch().
The final result in a console will be absolutely identical to what we saw when we sent a AJAX/XMLHttpRequest above.