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>
<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();
            theData = this.responseText;
            document.getElementById("demo").innerHTML = theData;
        request.open('GET', 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&pretty=true');


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.

Only if you use the script locally or the site is non-secure. You will not be able to use this script on a secure (https) site.

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?
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?

The point is both the place requesting and the API must both be the same (either both http or both https). It can not be mixed. It works locally, because using live server locally is http and the API is http. If you were to host the script on an https site, it would not work because the API is http. There is no way around this unless you use a proxy server to make the request for you instead of a browser making the request.

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

It is located at http://www.filltext.com

The filltext site would have to create a secure route instead of the http one currently being offered.