Build a Random Quote Machine, I'm Stuck

Build a Random Quote Machine, I'm Stuck
0

#1

I have this code and when I request the data from this website I don’t have any problem, but when I try to use another APIs to create a random text, I can’t,

I’m not sure What I’m doing wrong, should I use other code, or is because I didn’t find any APIs without restrictions?

Thank you so much for the help!

document.getElementById('button1').addEventListener('click', myf)

function myf(){
    var xhr = new XMLHttpRequest()

    xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true)

    xhr.onload = function (){
        if(this.status == 200){
            document.getElementById('the-text').innerHTML = this.responseText
        }
    }

    xhr.send()
}

#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

Thank you ! sorry it is my first post.


#4

Not sure what you mean by “but when I try to use another APIs to create a random text, I can’t” What other API are you trying to use that is not working? When I run the code you provided, it will display the response as text in the div with id=‘the-text’? When you run the above code, what happens?

Also, do you have a link to the entire code (html, css, and JavaScript)? That way, we don’t have to create html for the elements you reference in your JavaScript code.


#5

At the end, I made it work with this APIs,
Tried with many others but always had errors in the console, thank you for the response.

document.getElementById('button1').addEventListener('click', myf)
// button click function
function myf(){
    // requesting the API from jsonplaceholder.com
    var xhr = new XMLHttpRequest()

    xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true)

    // Using the API
    xhr.onload = function (){
        // IF the API is ok ...
        if(this.status == 200){
            //taking the JSON data into the var onj
            var obj = JSON.parse(this.responseText)
            // empty var 
            var res = ''
            // loop into the object var 
            for(var i in obj){
                // adding all the values to the empty var res
                res += obj[i].body             
            }
            //creating a random number!
            var ran = Math.floor((Math.random() * 10) + 1)

            //Sending the random text to the P tag with the id the-text
            // res.split(' ') making an array with all the values by word
            // [ran] raking a random positon of the res array
            document.getElementById('the-text').innerHTML = res.split(' ')[ran]
            
           

        }
    }
    //endind the request
    xhr.send()

    
}

```