@@ -86,7 +86,17 @@ Topics included/covered
86
86
- 2.5. [ GET vs POST method] ( #25-get-vs-post-method )
87
87
- 2.6. [ XMLHttpRequest-onreadystatechange] ( #26-xmlhttprequest-onreadystatechange )
88
88
89
- 3 . [ AJAX Reference and Resources] ( #3-ajax-reference-and-resources )
89
+ 3 . [ AJAX Live Demo Example] ( #3-ajax-live-demo-example )
90
+ - 3.1. [ XMLHttpRequest-Get Post Data-Basic] ( #31-xmlhttprequest-get-post-data-basic )
91
+ - 3.2. [ XMLHttpRequest-Get Post Data-Advanced] ( #32-xmlhttprequest-get-post-data-advanced )
92
+
93
+ 4 . [ JavaScript Http Request with fetch() API and Promises] ( #4-javascript-http-request-with-fetch()-api-and-promises )
94
+ - 4.1. [ Introduction to fetch() api] ( #41-introduction-to-fetch()-api )
95
+ - 4.2. [ fetch() api demo example] ( #42-fetch()-api-demo-example )
96
+
97
+ 5 . [ JavaScript Http Request with Axiox library] ( #5-javascript-http-request-with-axiox-library )
98
+
99
+ 6 . [ AJAX Reference and Resources] ( #6-ajax-reference-and-resources )
90
100
91
101
1 Introduction to AJAX
92
102
=====================
@@ -629,7 +639,349 @@ function loadData() {
629
639
```
630
640
631
641
632
- 3 AJAX Reference and Resources
642
+ 3 AJAX Live Demo Example
643
+ =====================
644
+
645
+ 3.1. XMLHttpRequest-Get Post Data-Basic
646
+ ---------------------
647
+
648
+ > ** Syntax & Example** : ` 3.1-xhr-req-res-live.html `
649
+
650
+ ``` html
651
+ <!DOCTYPE html>
652
+ <html lang =" en" >
653
+
654
+ <head >
655
+ <meta charset =" UTF-8" >
656
+ <meta name =" viewport" content =" width=device-width, initial-scale=1.0" >
657
+ <meta http-equiv =" X-UA-Compatible" content =" ie=edge" >
658
+ <title >3.1-xhr-req-res-live.html</title >
659
+
660
+ <link type =" text/css" rel =" stylesheet" href =" styles.css" >
661
+ <!-- Without async or defer , browser will run your script immediately, before rendering the elements that's below your script tag. -->
662
+ <script type =" text/javascript" src =" 3.1-xhr-req-res-live.js" defer ></script >
663
+
664
+ </head >
665
+
666
+ <body >
667
+
668
+ <section class =" button-container" >
669
+ <button id =" getButton" class =" button" >GET DATA</button >
670
+ <button id =" postButton" class =" button" >POST LOGIN DATA</button >
671
+ </section >
672
+
673
+ </body >
674
+
675
+ </html >
676
+ ```
677
+
678
+ <hr />
679
+
680
+ > ** Syntax & Example** : ` 3.1-xhr-req-res-live.js `
681
+
682
+ ``` js
683
+ console .log (' 3.1-xhr-req-res-live.js loaded' );
684
+
685
+ // get buttons from html/DOM
686
+ const getButton = document .getElementById (' getButton' );
687
+ const postButton = document .getElementById (' postButton' );
688
+
689
+ // define function to get data
690
+ fn_getData = () => {
691
+ console .log (' getButton clicked - in fn_getData' );
692
+
693
+ var xhr = new XMLHttpRequest ();
694
+ // use fake rest api `https://reqres.in/`, below url get list of users
695
+ xhr .open (' GET' , ' https://reqres.in/api/users' );
696
+
697
+ // convert XMLHttpRequest results to 'json' bydefault
698
+ xhr .responseType = ' json' ;
699
+
700
+ xhr .onload = () => {
701
+ let results = xhr .response ;
702
+ console .log (' results:' , results);
703
+
704
+ // convert string data to json/javascript object - ommit by using xhe.responseType = 'json'
705
+ // const jsonData = JSON.parse(results);
706
+ // console.log('jsonData:', jsonData);
707
+ }
708
+
709
+ xhr .send ();
710
+ }
711
+
712
+ // define function to post/send data
713
+ fn_postData = () => {
714
+ console .log (' postButton clicked - in fn_postData' );
715
+
716
+ const postData = {
717
+ " email" : " eve.holt@reqres.in" ,
718
+ " password" : " pistol"
719
+ };
720
+
721
+ var xhr = new XMLHttpRequest ();
722
+ // use fake rest api `https://reqres.in/`, below url get list of users
723
+ xhr .open (' POST' , ' https://reqres.in/api/register' );
724
+
725
+ // convert XMLHttpRequest results to 'json' bydefault
726
+ // xhr.responseType = 'json';
727
+ xhr .setRequestHeader (" Content-Type" , " application/json; charset=UTF-8" );
728
+
729
+ xhr .onload = function () {
730
+ var results = JSON .parse (xhr .responseText );
731
+ console .log (results);
732
+
733
+ };
734
+
735
+ xhr .send ((JSON .stringify (postData)));
736
+ }
737
+
738
+ // add event listener to button
739
+ getButton .addEventListener (' click' , fn_getData);
740
+ postButton .addEventListener (' click' , fn_postData);
741
+ ```
742
+
743
+
744
+ 3.2. XMLHttpRequest-Get Post Data-Advanced
745
+ ---------------------
746
+
747
+ > ** Syntax & Example** : ` 3.2-xhr-req-res-live-advanced.html `
748
+
749
+ ``` html
750
+ <!DOCTYPE html>
751
+ <html lang =" en" >
752
+
753
+ <head >
754
+ <meta charset =" UTF-8" >
755
+ <meta name =" viewport" content =" width=device-width, initial-scale=1.0" >
756
+ <meta http-equiv =" X-UA-Compatible" content =" ie=edge" >
757
+ <title >3.2-xhr-req-res-live-advanced.html</title >
758
+
759
+ <link type =" text/css" rel =" stylesheet" href =" styles.css" >
760
+ <!-- Without async or defer , browser will run your script immediately, before rendering the elements that's below your script tag. -->
761
+ <script type =" text/javascript" src =" 3.2-xhr-req-res-live-advanced.js" defer ></script >
762
+
763
+ </head >
764
+
765
+ <body >
766
+
767
+ <section class =" button-container" >
768
+ <button id =" getButton" class =" button" >GET DATA</button >
769
+ <button id =" postButton" class =" button" >POST LOGIN DATA</button >
770
+ </section >
771
+
772
+ <section class =" user-container" >
773
+ <h1 class =" user-name" ></h1 >
774
+ <span class =" user-email" ></span > <br /> <br />
775
+ <img class =" user-image" src =" " />
776
+ </section >
777
+
778
+ </body >
779
+
780
+ </html >
781
+ ```
782
+
783
+ <hr />
784
+
785
+ > ** Syntax & Example** : ` 3.2-xhr-req-res-live-advanced.js `
786
+
787
+ ``` js
788
+ console .log (' 3.2-xhr-req-res-live-advanced.js loaded' );
789
+
790
+ // get buttons from html/DOM
791
+ const getButton = document .getElementById (' getButton' );
792
+ const postButton = document .getElementById (' postButton' );
793
+
794
+ // common function to send receive http call
795
+ const fn_sendhttpRequest = (httpMethod , httpUrl , data ) => {
796
+ // promise
797
+ const httpPromise = new Promise ((resolve , reject ) => {
798
+
799
+ const xhr = new XMLHttpRequest ();
800
+
801
+ // use fake rest api `https://reqres.in/`, below url get list of users
802
+ xhr .open (httpMethod, httpUrl);
803
+
804
+ // convert XMLHttpRequest results to 'json' bydefault
805
+ xhr .responseType = ' json' ;
806
+
807
+ if (data) {
808
+ xhr .setRequestHeader (" Content-Type" , " application/json; charset=UTF-8" );
809
+ }
810
+
811
+ xhr .onload = () => {
812
+ if (xhr .status >= 400 ) {
813
+ reject (xhr .response );
814
+ } else {
815
+ resolve (xhr .response );
816
+ }
817
+ }
818
+
819
+ xhr .onerror = () => {
820
+ reject (' Please verify...something went wrong!' );
821
+ }
822
+
823
+ xhr .send (JSON .stringify (data));
824
+
825
+ });
826
+
827
+ return httpPromise;
828
+
829
+ }
830
+
831
+ // define function to get data
832
+ const fn_getData = () => {
833
+ console .log (' getButton clicked - in fn_getData' );
834
+
835
+ fn_sendhttpRequest (' GET' , ' https://reqres.in/api/users' ).then (respenseResultData => {
836
+ console .log (' respenseResultData:' , respenseResultData);
837
+ document .getElementsByClassName (' user-name' )[0 ].innerHTML = respenseResultData .data [0 ].first_name + ' ' + respenseResultData .data [0 ].last_name ;
838
+ document .getElementsByClassName (' user-email' )[0 ].innerHTML = respenseResultData .data [0 ].email ;
839
+ document .getElementsByClassName (' user-image' )[0 ].src = respenseResultData .data [0 ].avatar ;
840
+ });
841
+
842
+ }
843
+
844
+ // define function to post/send data
845
+ const fn_postData = () => {
846
+ console .log (' postButton clicked - in fn_postData' );
847
+
848
+ const postLoginData = {
849
+ " email" : " eve.holt@reqres.in" ,
850
+ " password" : " pistol"
851
+ };
852
+
853
+ fn_sendhttpRequest (' POST' , ' https://reqres.in/api/register' , postLoginData).then (respenseResultData => {
854
+ console .log (' respenseResultData:' , respenseResultData);
855
+ }).catch (err => {
856
+ console .log (' errors: ' , err);
857
+ });
858
+
859
+ }
860
+
861
+ // add event listener to button
862
+ getButton .addEventListener (' click' , fn_getData);
863
+ postButton .addEventListener (' click' , fn_postData);
864
+ ```
865
+
866
+
867
+ 4 JavaScript Http Request with fetch() API and Promises
868
+ =====================
869
+
870
+ 4.1. Introduction to fetch() api
871
+ ---------------------
872
+ - Fetch is a new, modern, promise-based API that lets us do Ajax requests without all the unnecessary complications associated with XMLHttpRequest
873
+ - ` fetch() API ` is a modern replacement for XMLHttpRequest, addition to the browser, better than xmlHttpRequest
874
+ - fetch API, which is a modern way to Ajax without helper libraries like jQuery or Axios
875
+ - The Fetch API provides a fetch() method defined on the window object, which you can use to perform requests. This method returns a Promise that you can use to retrieve the response of the request
876
+ - ` fetch() ` is the globally available method/function made available/provided by the browser for sending http-request
877
+ - Browser support: Support for Fetch is pretty good! All major browsers (exception of Opera Mini and old IE) support it natively, which means we can safely use it in our projects (older browser does not support!)
878
+
879
+
880
+ 4.2. fetch() api demo example
881
+ ---------------------
882
+
883
+ > ** Syntax & Example** : ` 4.2-fetch-api.html `
884
+
885
+ ``` html
886
+ <!DOCTYPE html>
887
+ <html lang =" en" >
888
+
889
+ <head >
890
+ <meta charset =" UTF-8" >
891
+ <meta name =" viewport" content =" width=device-width, initial-scale=1.0" >
892
+ <meta http-equiv =" X-UA-Compatible" content =" ie=edge" >
893
+ <title >4.2-fetch-api</title >
894
+
895
+ <link type =" text/css" rel =" stylesheet" href =" styles.css" >
896
+ <!-- Without async or defer , browser will run your script immediately, before rendering the elements that's below your script tag. -->
897
+ <script type =" text/javascript" src =" 4.2-fetch-api.js" defer ></script >
898
+
899
+ </head >
900
+
901
+ <body >
902
+
903
+ <section class =" button-container" >
904
+ <button id =" getButton" class =" button" >GET DATA</button >
905
+ <button id =" postButton" class =" button" >POST LOGIN DATA</button >
906
+ </section >
907
+
908
+ <section class =" user-container" >
909
+ <h1 class =" user-name" ></h1 >
910
+ <span class =" user-email" ></span > <br /> <br />
911
+ <img class =" user-image" src =" " />
912
+ </section >
913
+
914
+ </body >
915
+
916
+ </html >
917
+ ```
918
+
919
+ <hr />
920
+
921
+ > ** Syntax & Example** : ` 4.2-fetch-api.js `
922
+
923
+ ``` javascript
924
+ console .log (' 4.2-fetch-api.js loaded' );
925
+
926
+ // get buttons from html/DOM
927
+ const getButton = document .getElementById (' getButton' );
928
+ const postButton = document .getElementById (' postButton' );
929
+
930
+ // define function to get data
931
+ const fn_getData = () => {
932
+ console .log (' getButton clicked - in fn_getData' );
933
+
934
+ fetch (' https://reqres.in/api/users' ).then (respenseResult => {
935
+ console .log (' respenseResult:' , respenseResult);
936
+ return respenseResult .json ();
937
+ })
938
+ .then (respenseResultData => {
939
+ console .log (' respenseResultData:' , respenseResultData);
940
+
941
+ document .getElementsByClassName (' user-name' )[0 ].innerHTML = respenseResultData .data [0 ].first_name + ' ' + respenseResultData .data [0 ].last_name ;
942
+ document .getElementsByClassName (' user-email' )[0 ].innerHTML = respenseResultData .data [0 ].email ;
943
+ document .getElementsByClassName (' user-image' )[0 ].src = respenseResultData .data [0 ].avatar ;
944
+ });
945
+
946
+ }
947
+
948
+ // define function to post/send data
949
+ const fn_postData = () => {
950
+ console .log (' postButton clicked - in fn_postData' );
951
+
952
+ const options = {
953
+ method: ' post' ,
954
+ headers: {
955
+ ' Content-type' : ' application/x-www-form-urlencoded; charset=UTF-8'
956
+ },
957
+ body: ' email=eve.holt@reqres.in&password=pistol'
958
+ }
959
+
960
+ fetch (' https://reqres.in/api/register' , options)
961
+ .then (respenseResult => {
962
+ console .log (' respenseResult:' , respenseResult);
963
+ return respenseResult .json ();
964
+ })
965
+ .then (respenseResultData => {
966
+ console .log (' respenseResultData:' , respenseResultData);
967
+ })
968
+ .catch (err => {
969
+ console .error (' Request failed' , err)
970
+ })
971
+
972
+ }
973
+
974
+ // add event listener to button
975
+ getButton .addEventListener (' click' , fn_getData);
976
+ postButton .addEventListener (' click' , fn_postData);
977
+ ```
978
+
979
+
980
+ 5 JavaScript Http Request with Axiox library
981
+ =====================
982
+
983
+
984
+ 6 AJAX Reference and Resources
633
985
=====================
634
986
635
987
> axios - https://github.com/axios/axios
0 commit comments