Why does my AJAX code to pull data from JSON url not working?

can somebody tell me what is wrong or missing from my code?
here is my code :

<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest test</h2>
<button id='btn' type="button" >Change Content</button>
<div id="demo"></div>
<div id="demo1"></div>

<script src="requester.js">
    document.getElementById('btn').addEventListener('click', function loadDoc(){
        document.getElementById("demo1").innerHTML = 'bla bla';
        const request = new XMLHttpRequest();
        request.onload(function(){
            theData = this.responseText;
            document.getElementById("demo").innerHTML = theData;
            
            
        });
        request.open('GET', 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&pretty=true');
        request.send();
    });
</script>

</body>
</html>

I took that url from www.filltext.com

You have many issues.

  1. <script src="requester.js"> This attempts to find a file named requester.js but if there is not one it will fail. Get rid of the src="requester.js" part.

  2. You need to assign a function to request.onload. You have tried to pass a function as an argument to request.onload which is not the same that as assigning a function to it.

  3. Lastly, if your domain hosting this code is secure (it originates from https, then you can not make a request to a non-secure site http. You will need to find another API that is own a secure site.

1 Like

Thank you, it can pull information from the json file on that url now.

I used live server and could retrieve data from a local json file, also i could retrieve data from that url which is http and not https.

But are you saying i can’t do it with https?
Why?
I mean the ajax object’s name is XMLHttp not XMLHttps right?

Any way please explain why.
Is there another script to use for an https url?

I can’t wrap my head around everything you say but where is the API located?
Or hiw to have/create an https API?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.