There seems to be a mysterious absence of chuck norris jokes in

I'm attempting to call two different APIs by clicking a button to display a random joke on the screen. I've created two separate functions to fetch the APIs and used Math.random() to generate a random number. If the number is greater than 50, one function is executed; otherwise, the other function is called. However, I'm encountering an issue where the Chuck Norris API data always returns Undefined, and I'm struggling to identify the mistake.

Below is my JavaScript code:

const button = document.getElementById("button");
const joke = document.getElementById("joke-content");
const url = "https://icanhazdadjoke.com/";
const urlChuck = "https://api.chucknorris.io/jokes/random";

button.addEventListener("click", getJoke = () => {
    const randomNumber = 100 * Math.random();
    return randomNumber > 50 ? getDadJoke() : getChuckJoke();
}
);

const getDadJoke = () => {
    fetch(url, {
        headers: {
            "Accept": "application/json"
        }
    }).then(response => response.json())
        .then(data => joke.innerHTML = data.joke)
}

const getChuckJoke = () => {
    fetch(urlChuck, {
        headers: {
            "Accept": "application/json"
        }
    }).then(response => response.json())
        .then(data => joke.innerHTML = data.joke)
}

Answer №1

When it comes to the legendary Chuck Norris joke, remember to use data.value instead of data.joke:

const retrieveChuckJoke = () => {
    fetch(uRlChUck, {
        headers: {
            "Accept": "application/json"
        }
    }).then(response => response.json())
        .then(data => joke.innerHTML = data.value)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the syntax for inserting a text (value) into a text input field in HTML using PHP?

I'm having trouble getting the input field to populate with "Hello" when the button is clicked. I've checked for a solution, but can't seem to find one. Any help would be appreciated. Thank you. <!DOCTYPE html> <html> <head&g ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

angularjs code to dynamically change the selected index of an option in a document

This code snippet demonstrates how to achieve this functionality using pure JavaScript: document.getElementById("mySelect").selectedIndex = "0" <select class="selectpicker" id="mySelect"> <option>English &nbsp;</option> < ...

Unable to modify variable values in AngularJS

I'm currently utilizing AngularJS along with the "Angular Material" implementation (found here: https://material.angularjs.org/latest/#/) One of the components I'm using is the SideNav component: https://material.angularjs.org/latest/#/demo/mate ...

The conditional statement for ajax is malfunctioning

I am encountering an issue with some ajax coding. The if condition is not working as expected - whenever the program runs, only the else statement gets executed even when the if statement should be satisfied. <script type="text/javascript> funct ...

Enhance your Vue.js application by dynamically adding a class when a computed value

Just delving into the world of vue.js and I have a simple query. I've been following a tutorial but now I'd like to add my own touch to it :-P Whenever there is a change in my rank, I would like to include a CSS class for animating the label. Ho ...

Tips for preventing duplicate properties in Material UI when using React JS

Incorporating components from Material-UI, I have designed a form where the state of inputs is controlled by the parent component. However, I encountered an error stating "No duplicate props allowed" due to having multiple onChange parameters. Is there a w ...

"Troubleshooting problems with converting XML to Json and deserializing objects - Could InfoPath namespaces

I am currently exploring the process of loading a large batch of InfoPath XML files into Cosmos DB as JSON files to test out a potential project. However, I am facing challenges when it comes to converting the XML files into JSON and then loading them back ...

Why is this loop in jQuery executing twice?

$(document).bind("ready", function(){ // Looping through each "construct" tag $('construct').each( alert('running'); function () { // Extracting data var jC2_events = $(this).html().spl ...

html scroll to the flickering page

Why is it that when a user clicks on a link in the list, the browser flickers? This issue becomes especially noticeable if a user clicks on the same 'link' twice. Is there a solution to prevent this from occurring? The problem also seems to aris ...

When using `setState()`, ensure that you are updating a component that is already mounted or in the process of mounting. If you receive this error, it

When using WebSocket to communicate with my server, I call the handleSubmit() function to send data and update my state based on the received response. Everything works fine initially. Upon calling componentWillUnmount, I stop sending data to the websocke ...

Tabs within the AutoComplete popup in Material-UI

Would it be feasible to showcase the corresponding data in the AutoComplete popover using Tabs? There could be potentially up to three categories of data that match the input value, and my preference would be to present them as tabs. Is there a way to in ...

Utilizing Bootstrap to allow for seamless text wrapping around a text input field

I am trying to implement a "fill-in-the-blank" feature using Bootstrap, where users need to enter a missing word to complete a sentence. Is there a way to align the text input horizontally and have the rest of the sentence wrap around it? This is my curr ...

What is the process for uploading a video to YouTube with JSON-C format?

While I have successfully uploaded videos to Youtube using their xml input/output format, I am finding their documentation on utilizing json-c for uploading to be lacking. Specifically, I am unsure of what the 'key' is for the json data that need ...

Troubleshooting focus loss in React input fields within a Datatable component implemented in a

I noticed an issue with my Datatable where the input field loses focus whenever I type a character and define the component inside another component. Surprisingly, when I directly place the component in the datatable, it works perfectly fine. I understand ...

unable to fix slideshow glitch after multiple cycles

I've encountered an issue with my custom JavaScript picture scroll. After 3-4 photo changes, the script crashes the page unexpectedly. I'm not sure what is causing this problem! Can someone provide assistance? Below is the code snippet: <di ...

unable to perform a specific binary operation

Is there an efficient method to achieve the following using binary operations? First byte : 1001 1110 Second byte : 0001 0011 Desired outcome : 1000 1100 I am looking to reset all bits in the first byte that correspond to bit values of 1 in the secon ...

Utilize React HOC (Higher Order Component) and Redux to retrieve data and pass it as props

In my quest to develop a Higher Order Component (HOC) that can execute methods to fetch data from the backend and display a loader mask during loading, I encountered a challenge. I aim to have the flexibility of passing different actions for various compon ...

Tips for finding information within a table using HTML

My task involves creating a table with the option for users to search data within it. However, I have encountered an issue where I am only able to search for data in the first row of the table. <table style="width:100%" id="table"> <tr> ...

Failure in AngularJS HTTP GET Request

My attempt at using Angular code to make a GET request to different APIs has been met with mixed results. While the code works perfectly when making a request to , it encounters issues when requesting from . The error message "SyntaxError: JSON.parse: une ...