1
+ //Ajax
2
+
3
+ let fetchBtn = document . getElementById ( 'fetchBtn' ) ;
4
+ fetchBtn . addEventListener ( 'click' , buttonHandler ) ;
5
+
6
+ function buttonHandler ( ) {
7
+ console . log ( 'You have clicked the fetchBtn' ) ;
8
+
9
+ // Instantiate the object
10
+ let xhr = new XMLHttpRequest ( ) ;
11
+
12
+ // Open the object
13
+ // xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);//async value is true
14
+
15
+
16
+ //Use this for post request
17
+ xhr . open ( 'POST' , 'http://dummy.restapiexample.com/api/v1/create' , true ) ;
18
+ xhr . getResponseHeader ( 'Content-type' , 'application/json' ) ;
19
+ // xhr ready states
20
+ // learn more about xhr ready states here - https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
21
+
22
+ xhr . onreadystatechange = function ( ) {
23
+ // console.log("xhr state is ", xhr.readyState);
24
+ }
25
+ //What to do on progress (optional)
26
+ xhr . onprogress = function ( ) {
27
+ console . log ( 'On progress' ) ;
28
+ }
29
+
30
+ //What to do when response is ready
31
+ xhr . onload = function ( ) {
32
+ if ( this . status == 200 ) { //Http status code which means OK
33
+ console . log ( this . responseText ) ;
34
+ } else {
35
+ console . log ( 'Some eror occured' ) ;
36
+ }
37
+ }
38
+ //You can refer this to know more about http status codes
39
+ // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
40
+
41
+ //send the data
42
+ paramater = `{"name":"test34sad545","salary":"123","age":"23"}` ;
43
+ xhr . send ( paramater ) ;
44
+ console . log ( 'Done' ) ; //this statement is printed first because async value is true
45
+
46
+ }
47
+
48
+ let populateBtn = document . getElementById ( 'populateBtn' ) ;
49
+ populateBtn . addEventListener ( 'click' , populateHandler ) ;
50
+
51
+ function populateHandler ( ) {
52
+ console . log ( 'You have clicked the populateBtn' ) ;
53
+
54
+ // Instantiate the object
55
+ let xhr = new XMLHttpRequest ( ) ;
56
+
57
+ // Open the object
58
+ xhr . open ( 'GET' , 'https://reqres.in/api/users?page=2' , true ) ; //async value is true
59
+
60
+ //What to do on progress (optional)
61
+ xhr . onprogress = function ( ) {
62
+ console . log ( 'On progress' ) ;
63
+ }
64
+
65
+ //What to do when response is ready
66
+ xhr . onload = function ( ) {
67
+ if ( this . status == 200 ) { //Http status code which means OK
68
+ let obj = JSON . parse ( this . responseText ) ;
69
+ // console.log(obj);
70
+ let list = document . getElementById ( 'list' ) ;
71
+ html = "" ;
72
+ obj = obj . data ;
73
+ console . log ( obj ) ;
74
+ for ( key in obj ) {
75
+ // console.log(key);
76
+ html += `<li> ${ obj [ key ] . first_name } </li>` ;
77
+ }
78
+ list . innerHTML = html ;
79
+ // console.log(html);
80
+ } else {
81
+ console . log ( 'Some eror occured' ) ;
82
+ }
83
+ }
84
+ //send the data
85
+ xhr . send ( ) ;
86
+ console . log ( 'Done' ) ; //this statement is printed first because async value is true
87
+
88
+ }
0 commit comments