11/* To show that data fetching is happening asynchronously (in the background), but not on initial page refresh */
22
3+ /*
4+ - JSON is the string format will "GET" from server or sent from browser "POST"
5+ - Since it is string we will need to "parse" when we get or "stringify" when sent to server
6+ */
7+
8+ const url = "./api/people.json" ;
9+
310const btn = document . querySelector ( ".btn" ) ;
411btn . addEventListener ( "click" , ( ) => {
5- getData ( ) ;
12+ getData ( url ) ;
613} ) ;
714
8- function getData ( ) {
15+ function getData ( url ) {
916 const xhr = new XMLHttpRequest ( ) ;
1017
11- xhr . open ( "GET" , "./api/sample.txt" ) ;
18+ xhr . open ( "GET" , url ) ;
1219
1320 /* It gets fired when since ready state changes from 0 to 1 when used open() method */
1421 xhr . onreadystatechange = function ( ) {
1522 // console.log(xhr);
1623 if ( xhr . readyState === 4 && xhr . status === 200 ) {
17- const paragraph = document . createElement ( "p" ) ;
18- paragraph . textContent = xhr . responseText ;
19- document . body . appendChild ( paragraph ) ;
24+ console . log ( xhr . responseText ) ;
25+
26+ const data = JSON . parse ( xhr . responseText ) ;
27+ console . log ( data ) ;
28+
29+ const displayPeople = data
30+ . map ( ( person ) => {
31+ return `<p>${ person . name } </p>` ;
32+ } )
33+ . join ( "" ) ;
34+
35+ const element = document . createElement ( "div" ) ;
36+ element . innerHTML = displayPeople ;
37+ document . body . appendChild ( element ) ;
2038 } else {
2139 console . log ( {
2240 status : xhr . status ,
@@ -31,4 +49,4 @@ function getData() {
3149}
3250
3351// It executes first, since the above functionality works asynchronously by browser, only when JavaScript is free then it takes the data from browser
34- console . log ( "hello world" ) ;
52+ // console.log("hello world");
0 commit comments