Fundamentals of the JavaScript fetch method for AJAX

  Рет қаралды 14,733

Steve Griffith - Prof3ssorSt3v3

Steve Griffith - Prof3ssorSt3v3

Күн бұрын

The latest (ES5 & ES6) way to make AJAX calls from JavaScript in your browser is with the fetch( ) command.
While the fetch( ) command is actually using JavaScript Promises, this video discusses fetch to explain how it works at a basic level without needed to understand Promises.
JavaScript Code GIST: gist.github.com/prof3ssorSt3v...
Video about Basic Promises: • JavaScript ES6 Promise...
Video about AJAX fundamentals: • What is AJAX and Why S...
AJAX fetch Playlist - • What is AJAX and Why S...

Пікірлер: 51
@rotrose7531
@rotrose7531 4 жыл бұрын
Second round, a sure way to understand fetch is to watch this tutorial again and again. Thank you.
@wadebanks8945
@wadebanks8945 4 жыл бұрын
Thumbs wayyyyy up. You make what others look like "impossible to do" very very easy
@martyoconnor7211
@martyoconnor7211 5 жыл бұрын
Thank you!! Every video I've seen by you has been phenomenal at breaking down and explaining concepts in a concise manner.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 5 жыл бұрын
Thanks! Please share the channel to help other people too. :)
@rotrose7531
@rotrose7531 4 жыл бұрын
Most AWESOME explanations about javascript! you teaching style leave no room for confusion. purely deserve our respect!
@fonncatalina6464
@fonncatalina6464 3 жыл бұрын
Thank you sir! Your channel is my oasis, when I get confuse I'm looking for your help😊.
@rongrongie5668
@rongrongie5668 6 жыл бұрын
Glad that I've looked over this, Thanks Steve. I didn't know that XmlHttpRequestObject was things of past , the course that I took wasn't being updated so they only taught Old Ajax request and used Jquery library over CDN to simplify the code using Jquery method.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 6 жыл бұрын
I'm glad you watched then too. The more people who learn about how to use fetch and stop using jQuery the happier I am.
@blackdev417
@blackdev417 3 жыл бұрын
Fantastic...you are a great teacher my friend.
@augustocaceressuarez6647
@augustocaceressuarez6647 4 жыл бұрын
Thank you. !!! You help me a lot . Thank you!
@21rogerwaters
@21rogerwaters 5 жыл бұрын
Great video. Thank you very much for share your knowledge with us =)
@chesterxp508
@chesterxp508 2 жыл бұрын
Brilliant tutorials :)
@marytyutyunnik1141
@marytyutyunnik1141 5 жыл бұрын
Thanx a lot!!!
@lovesteve1400
@lovesteve1400 3 жыл бұрын
Keep going pro ☺️💞
@parsahosseini4241
@parsahosseini4241 5 жыл бұрын
Man, you are AWESOME!!! please keep making tutorials, and a question, why when I do this: fetch(req).then((response) => { console.log(response.json()); }) I get the promise back, but when I do this: fetch(req).then((response) => { return response.json(); }).then((data) => { console.log(data); }) I get the right data. Thanks a LOT:)
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 5 жыл бұрын
response.json() is an async method that returns a Promise. Your second then( ) function is not returning anything, it just console logs the data that was returned by the response.json( ) promise.
@imindproduction9484
@imindproduction9484 4 жыл бұрын
Thank you Steve for your great tutorials and i have a question after generating a random number what's the condition code to control if the number more than 10 show an error and if the number less than 10 continue ?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
You can use a basic if statement around the fetch. See the question from @kapkaal below and @kyle humphrey's answer.
@Kodeispoetry
@Kodeispoetry 3 жыл бұрын
Excellent video, but please work on focus screen - font too small to see.
@melik-alexandrefarhat2185
@melik-alexandrefarhat2185 4 жыл бұрын
Hello! Thx Steve for this tutorial. Simple question : why did you use a second .then( ) ? Why not put all the code in the first .then( ) ? I guess you did that for demonstration purposes to show that you ca pass the return of a .then( ) to the next .then( ) ?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
The method res.json( ) returns a promise. So, we need to wrap it in the then method too.
@cybermoongamer1071
@cybermoongamer1071 5 жыл бұрын
Your video was very helpful. Now I do have a small question, if an API key is requested how can I implement that API key in the code? I know that with XMLHttpRequest(); I can use xhr.setRequestHeader("x-api-key", "My_Key_Goes_Here"); but I can't figure out how to do the same but using fetch() instead the of XMLHttpRequest(); Any advice would be really appreciated.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 5 жыл бұрын
I have a series on AJAX and Fetch with videos about Headers and Request objects that work with fetch. You will have to create a Header object and then call the append( ) method to set the API entry. Then add the Header object to the Request object.
@michaelwaldron9232
@michaelwaldron9232 3 жыл бұрын
Steve, I know a lot of time has passed since posting this, and version issues might be the problem, but I followed the instruction to add the node-fetch package. When I run the js, I get "fetch is not define" , so I uncomment the "let fetch" line 7 and executes, and i see user data in js but error then follows, "require is not defined" does this even make sense? I get no output on html side
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 жыл бұрын
Node-fetch needs to be installed with npm in the current project folder and then the require command can import the fetch command.
@jawadeladnani6248
@jawadeladnani6248 4 жыл бұрын
Thank you very much sir for ur videos .. i have one question , i tried to do this : fetch(url).then((resp) =>{ console.log(JSON.stringify(resp.json())); }) isn't that the same as : fetch(url).then((resp) =>{ return resp.json(); }).then((data) =>{ console.log(JSON.stringify(data)); }) but it doesnt work , can you explain me why ?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
Sure. resp.json( ) is an asynchronous method. It returns a promise, not the actual value. You need the second then( ) to wait for the result of resp.json()
@kapkaal
@kapkaal 5 жыл бұрын
Nicely explained..i have one doubt How did u get invalid for id above 10..math.random generates numbers between 1 to 20..nowhere its mentioned to show error abv id no 10
@kylerhumphrey
@kylerhumphrey 5 жыл бұрын
the url where he is requesting the data from only has json objects. There are many objects however there user Ids for these objects only go to 10. So if he tries to get information from 11-20 it doesn't exist and results in 404
@kapkaal
@kapkaal 5 жыл бұрын
Thanx kyle..eventualy as i watched further videos on fetch and json and ajax things became clear..😀
@CesarJuarezVargas
@CesarJuarezVargas 6 жыл бұрын
When replicating it, I could see the results on the Console tab, but nothing is displayed on the html document screen. Why could it be?
@CesarJuarezVargas
@CesarJuarezVargas 6 жыл бұрын
RECALL: syntax review.
@froneotm9565
@froneotm9565 2 жыл бұрын
That's probably because you haven't added the div id
@CesarJuarezVargas
@CesarJuarezVargas 6 жыл бұрын
Can Ajax calls be used to retrieve other Ajax calls?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 6 жыл бұрын
You are over thinking this. Modern AJAX is single method - fetch( ). It goes and fetches a single file from a web server somewhere. That's all.
@CesarJuarezVargas
@CesarJuarezVargas 6 жыл бұрын
First time coding JS for me. It can get quite overwhelming.=(
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 6 жыл бұрын
Cesar Juarez-Vargas it's just matter of practicing and experimenting until it makes sense
@zooneyl2248
@zooneyl2248 2 жыл бұрын
Does it always generate an error for IDs > 10? Coz i don't see any code here to make it happen on purpose.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 2 жыл бұрын
That is just the jsonplaceholder website. It has a static set of json files that use the same ids all the time. jsonplaceholder.typicode.com/ if you want the information about an existing user, the only ones that exist are ids 1 - 10.
@bhagabatsahoo3112
@bhagabatsahoo3112 2 жыл бұрын
Hi Steve, any user id higher than 10 will generate a 404 error - how browser understands this ? sorry, i am not able to get it... please
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 2 жыл бұрын
That's the JSON placeholder website that only accepts ids up to 10.
@bhagabatsahoo3112
@bhagabatsahoo3112 2 жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 Thank you. i loved your way of teaching... subscribed your channel. could you please make videos on typescript if possible?
@It_guy613
@It_guy613 Жыл бұрын
I am watching this full playlist to learn more about AJAX requests, but something that bugged me out was when you said "turn into a json" with response.json() method, but what that actually does is get the Json and then convert it into a javascript object.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
Yes. I misspoke with my simplification. To be explicit with all the details... The fetch method returns a Promise that will resolve with a Response object. The Response object has a body property which is a Body object that contains a file, which contains a String which is formatted as JSON. The Response object has an asynchronous json() method will extract the JSON formatted string from the body of the returned file and convert that JSON formatted String into a JavaScript object. This will also be wrapped in a Promise. The Promise created by response.json() is returned from the first then( ) and is passed to the next then( ) method's function.
@It_guy613
@It_guy613 Жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 by wrapped in a promise you mean that the object promise will resolve if succesfull, and then when you convert the json into a js object, that is still part of the promise, meaning it will still execute the second then method as part of the promise since it was resolved or does the first then method returns a new promise to the next then method?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
@@It_guy613 response.json() returns a Promise object which is the return value of the function inside the first then( ). The first then( ) accepts the return value from the function and wraps that in a new Promise object. Now you have two Promise objects - one inside the other. These will be flattened into a single Promise object automatically. The flattened Promise object will resolve into the JS Object that was created from the JSON formatted string. This will trigger the next then( ) method and the JS Object will be passed to the next function as a parameter. If for some reason the flattened Promise fails and is rejected then the catch() method will be triggered instead of the then() method.
@It_guy613
@It_guy613 Жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 so basically the fetch() method creates a new promise, ok, and when it resolves(if status is ok) the fetch returns this new promise for the first then() method. The first then() receives the return statement from the fetch() (which is a promise) and uses it as a parameter. For the first then(), it's return statement returns a new promise for the second then() to use as a parameter? So basically there are two promises, one created by the fetch and the second one created by the first then()? So i assume that after each then() it will create a new fresh promise but in the end it will get all the promises together into one.... ? Sorry i am a beginner and i am really trying to get my head around promises, i am at episode 4 of this playlist i guess, so i do not know much about promises other than it is a condicional statement to execute based on the server response.
@Kapreski
@Kapreski 4 жыл бұрын
9:42 so fetch() returns a promise and then() is a method of that object all fine and dandy the question is how the response argument/object got passed automatically to then(), I mean you just wrote 'response' and it recognizes it as the response object as if it were predefined somewhere in the script.. this reminds me of the event object when it get passed to the callback function in a similar way.. cool but how?!
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
Fetch returns a promise. A promise either resolves or rejects. Which means it will call then or catch. When then or catch get called a value will be passed. Check out my playlist on Promises to understand more.
@KushEzio
@KushEzio 4 жыл бұрын
101 likes
@DmitriyMalayevProfile
@DmitriyMalayevProfile 3 жыл бұрын
/* basic fetch using jsonplaceholder for the data Remember that fetch returns a promise HTTP status codes - www.restapitutorial.com/httpstatuscodes.html to test with NODE we need to install the node-fetch package npm install node-fetch let fetch = require('node-fetch'); */ //get the details for a random user const root = 'jsonplaceholder.typicode.com'; let id = Math.floor(Math.random() * 20) + 1; //id 1 to 20 Math.random() generates a number between 0.001 and 0.999 let uri = root + '/users/' + id; console.log('FETCH: ', uri); //any user id higher than 10 will generate a 404 error fetch( uri ) .then( function( response ){ //response contains json code if(response.status == 200){ //response is a variable name that can be anything we'd like. JSON is inside of it. return response.json(); //Reads the contents of the file and extract the text and convert it into JSON }else{ throw new Error('Invalid user ID'); } }) .then( (data) =>{ //data is the JSON that's returned by the .then above console.log( data ); let jsonData = JSON.stringify(data); //String version of the data console.log(data); let output = document.getElementById('output'); //output is the div id output.textContent = jsonData; } ) .catch( (err)=>{ //If there is any kind of error above, this will run. console.log('ERROR: ', err.message); } );
JavaScript Fetch with Request and Headers Objects
16:26
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 64 М.
Combining Async Await with Promises
9:10
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 7 М.
Double Stacked Pizza @Lionfield @ChefRush
00:33
albert_cancook
Рет қаралды 115 МЛН
Survive 100 Days In Nuclear Bunker, Win $500,000
32:21
MrBeast
Рет қаралды 76 МЛН
Задержи дыхание дольше всех!
00:42
Аришнев
Рет қаралды 3,7 МЛН
Async JS Crash Course - Callbacks, Promises, Async Await
24:31
Traversy Media
Рет қаралды 1,4 МЛН
Why The Windows Phone Failed
24:08
Apple Explained
Рет қаралды 172 М.
Real World AJAX Fetch to Live HTML & CSS
13:47
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 4,3 М.
Fetch API in JavaScript for AJAX Developers
11:25
dcode
Рет қаралды 27 М.
Ten Steps to Mastering the Fetch API
2:19:52
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 43 М.
Asynchronous JavaScript Crash Course
1:28:03
Codevolution
Рет қаралды 197 М.
Real World Array Method Uses in JavaScript Web Development
24:18
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 12 М.
AJAX Crash Course (Vanilla JavaScript)
1:09:43
Traversy Media
Рет қаралды 719 М.
Double Stacked Pizza @Lionfield @ChefRush
00:33
albert_cancook
Рет қаралды 115 МЛН