Fundamentals of the JavaScript fetch method for AJAX

แชร์
ฝัง
  • เผยแพร่เมื่อ 15 ต.ค. 2024

ความคิดเห็น • 51

  • @rotrose7531
    @rotrose7531 4 ปีที่แล้ว +1

    Second round, a sure way to understand fetch is to watch this tutorial again and again. Thank you.

  • @martyoconnor7211
    @martyoconnor7211 6 ปีที่แล้ว +8

    Thank you!! Every video I've seen by you has been phenomenal at breaking down and explaining concepts in a concise manner.

  • @blackdev417
    @blackdev417 3 ปีที่แล้ว

    Fantastic...you are a great teacher my friend.

  • @fonncatalina6464
    @fonncatalina6464 3 ปีที่แล้ว +1

    Thank you sir! Your channel is my oasis, when I get confuse I'm looking for your help😊.

  • @rotrose7531
    @rotrose7531 4 ปีที่แล้ว

    Most AWESOME explanations about javascript! you teaching style leave no room for confusion. purely deserve our respect!

  • @wadebanks8945
    @wadebanks8945 5 ปีที่แล้ว

    Thumbs wayyyyy up.
    You make what others look like "impossible to do" very very easy

  • @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.

  • @maf2525
    @maf2525 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 ปีที่แล้ว +1

      The method res.json( ) returns a promise. So, we need to wrap it in the then method too.

  • @augustocaceressuarez6647
    @augustocaceressuarez6647 4 ปีที่แล้ว +1

    Thank you. !!! You help me a lot . Thank you!

  • @parsahosseini4241
    @parsahosseini4241 6 ปีที่แล้ว +2

    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  6 ปีที่แล้ว +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.

  • @Kodeispoetry
    @Kodeispoetry 4 ปีที่แล้ว

    Excellent video, but please work on focus screen - font too small to see.

  • @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 ปีที่แล้ว +1

      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 ปีที่แล้ว +1

      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()

  • @chesterxp508
    @chesterxp508 3 ปีที่แล้ว

    Brilliant tutorials :)

  • @imindproduction9484
    @imindproduction9484 5 ปีที่แล้ว

    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  5 ปีที่แล้ว

      You can use a basic if statement around the fetch. See the question from @kapkaal below and @kyle humphrey's answer.

  • @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.

  • @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.

  • @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.

  • @21rogerwaters
    @21rogerwaters 6 ปีที่แล้ว

    Great video. Thank you very much for share your knowledge with us =)

  • @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 ปีที่แล้ว +1

      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..😀

  • @lovesteve1400
    @lovesteve1400 3 ปีที่แล้ว

    Keep going pro ☺️💞

  • @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 ปีที่แล้ว +1

      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?

  • @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.

  • @CesarJuarezVargas
    @CesarJuarezVargas 7 ปีที่แล้ว

    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 7 ปีที่แล้ว

      RECALL: syntax review.

    • @froneotm9565
      @froneotm9565 3 ปีที่แล้ว

      That's probably because you haven't added the div id

  • @CesarJuarezVargas
    @CesarJuarezVargas 7 ปีที่แล้ว

    Can Ajax calls be used to retrieve other Ajax calls?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  7 ปีที่แล้ว

      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 7 ปีที่แล้ว

      First time coding JS for me. It can get quite overwhelming.=(

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  7 ปีที่แล้ว

      Cesar Juarez-Vargas it's just matter of practicing and experimenting until it makes sense

  • @marytyutyunnik1141
    @marytyutyunnik1141 5 ปีที่แล้ว

    Thanx a lot!!!

  • @KushEzio
    @KushEzio 4 ปีที่แล้ว +1

    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);
    } );