0

I want to load dynamically content on my page using promise in javascript.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>Main</title>
        <script type="text/javascript">

            function func(url){
                return new Promise(function(resolve, reject) {
            
                    var request = new XMLHttpRequest();
                    request.open('GET', url);
                    request.onload = function() {
                        if (request.status == 200){
                            resolve(request.response);
                        } else {
                            reject(Error(request.statusText));
                        }
                    };
            
                    request.onerror = function() {
                        reject(Error("Network Error"))
                    };
            
                });
            }

            $(document).ready(function() {
                func('hello.html');
            });

        </script>
    </head>
    <body>
        
    </body>
</html>

I have hello.html file in the same folder and want to load it using func(). Is it the correct way to do it?

code_rushh
  • 37
  • 1
  • 8
  • Seems fine. Does it work for you? Notice that you call the function but do nothing with its result. Try attaching a `.then()` callback to the returned promise! – Bergi Apr 11 '22 at 19:13
  • There is already an API for making a request and getting a promise: [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) – trincot Apr 11 '22 at 19:14
  • I've closed this as a duplicate of [How do I promisify native XHR?](https://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr), which should validate your implementation and show some alternatives. Please [edit] your question to ask about a specific problem if that is not sufficient as an answer. If there is no problem with your code, consider posting at [codereview.SE], but check their rules first. – Bergi Apr 11 '22 at 19:15
  • You're using `$(document).ready(function(){…})` but have not loaded the jQuery library on your page. You'll want to [use some](https://stackoverflow.com/q/799981/1048572) [native version](https://stackoverflow.com/q/9899372/1048572) of this instead. – Bergi Apr 11 '22 at 19:18

0 Answers0