Using ajax to retrieve quotes and authors from online sources

I've recently started learning javascript and I'm currently working on the Random Quote Machine project on freecodecamp. The main goal is to show a random quote along with its author when the user clicks the "New Quote" button. However, I'm facing an issue where every time the button is clicked, it displays the quote in gibberish and I'm unsure of how to correctly fetch the quote and author. Any guidance on the right approach would be highly appreciated!

https://codepen.io/leafbow/pen/RyjaeV

$(document).ready(function() {
    $("#changeColor").on("click", function()  {
      getQuote();
    });
});

function getQuote() {
  var options = {
    url: 'https://quotesondesign.com/wp-json/posts? filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=getQuote'
  };

  var request = $.ajax(options); 

  request.done(function(responseFromServer) {
    console.log(responseFromServer);
    document.getElementById("quote").innerHTML = responseFromServer;
  });

  request.fail(function(responseFromServer, status, error) {
    console.log(responseFromServer);
    console.log(status);
    console.log(error);
  });
}

Answer №1

The information provided is not gibberish. The server sends back data in JSON format, which must be parsed to be utilized effectively.

Give this code a try:

request.done(function(responseFromServer) {
  var quote = responseFromServer[0];
  document.getElementById("quote").innerHTML = quote.title;
});

Furthermore, ensure to update the request URL. I found this information in the documentation.

Remove the _jsop parameter and include an empty callback parameter. Here is the updated URL:

https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=

Check out this live example for more details.

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

Issue with default behavior of infinite scroll in Angular 4

I'm currently working on incorporating infinite scroll into my Angular 4 application. I've carefully followed all the guidelines provided on https://www.npmjs.com/package/ngx-infinite-scroll According to the documentation: By default, the dir ...

Strategies for distinguishing between when a user closes a browser tab or refreshes the page

I'm currently in the process of developing a multiplayer game app using vue.js. For state management, I've opted to utilize vuex and for the backend server, I have integrated Firestore. A crucial aspect of the app is handling user interactions w ...

How do I go about configuring the uploaded image?

Here is a sample of my HTML code: <div class="images"> <figure> <button id="upload-add-product" class="icon-plus"></button> <input id="upload-file" type="file" style="display: none;" multiple/> </fi ...

Unusual characteristics of decision-making

Here is a snippet of my JavaScript code: function getSelectedText(){ if(window.getSelection){ select = window.getSelection().getRangeAt(0); var st_span = select.startContainer.parentNode.getAttribute("id").split("_") ...

Is it possible for a d3 chart to render twice in one area if it's rendered in two different places?

When attempting to showcase two distinct d3 pie charts on my webpage within individual mat-cards, they both end up displaying in the svg tag of the first d3 chart in my code. This is what my code looks like: <section class="three"> <! ...

Guide to creating a new browser tab in Java Script with customizable parameters

Here is a function I created to open a new window with a specific URL and pass certain parameters. function viewWeightAge() { var userNIC = document.getElementById("NICNo"); var childName = document.getElementById("c ...

Cannon.JS ensures that walls are impenetrable

I am currently experimenting with three.js and cannon.js, but I have encountered an issue where I am unable to create solid walls or any stationary objects that can block the player's movement. Below is the code I have been working on so far. I would ...

Attaching this to the event listener in React JS

After delving into a beginner's guide on React JS, I encountered a slight hiccup. The issue revolves around a simple problem within the button element; specifically, an event handler that requires passing an argument. This handler serves the purpose o ...

AngularJS seems to be failing to display the initial option in the input select field

When using Angularjs, binding an input select to the model results in a new empty option being created <option value="? undefined:undefined ?"></option> Here is an example of the code: <select name="category" ng-model="hotspot.category"&g ...

The battle of speed: ReactJS showdown between componentWillMount and render functions

export class Dashboard extends React.Component<DashboardProps, IMonthlyCommission>{ constructor(props) { super(props); this.state = {}; } componentWillMount() { request.get("AffiliateCommissionStatement/GetCommis ...

Counting the number of visible 'li' elements on a search list: A guide

In the following code snippet, I am attempting to create a simple search functionality. The goal is to count the visible 'li' elements in a list and display the total in a div called "totalClasses." Additionally, when the user searches for a spec ...

Comparison between JavaScript Promise .then(onFulfilled, onRejected) and .then(onFulfilled).catch(errorFunc) in handling asynchronous operations

As I was reviewing promises, I had a question about the order in which the .then/catch calls are executed when using the code below. Are the catch calls being placed at the end of the queue stack? I already have a clear understanding of the distinction bet ...

Fetching a destination through the post approach

Typically, we utilize window.location.href="/index.php?querystring"; in JavaScript. Is it possible to transmit the querystring via a POST method without including any form within the document? ...

Slow loading time when switching between items in the drop-down menu from the Main Menu

Visiting my website at europebathroom.com, you will notice a horizontal main menu with dropdown functionality. When hovering over a menu item, the corresponding dropdown appears seamlessly. Yet, sometimes quickly touching another menu item unintentionally ...

Steps for serializing HTML tags contained within a Form along with the Form itself

I am currently working on a form that allows users to input information for publication on the site. The form utilizes a combination of inline editing with contenteditable=true on editable HTML tags, as well as standard form inputs like selects and text fi ...

Attempting to eliminate the padding from the unordered list (ul) element within the pop-up box

Upon clicking the chip with chipName="button test IPA", a popup window appears. I am attempting to remove the padding from the ul tag within that popup. The issue I'm facing is that I cannot locate the ul tag in my HTML or JSX code. I have assigned a ...

Is there a way to change a string that says "False" into a Boolean value representing false?

When retrieving values from the backend, I am receiving them as strings 'True' and 'False'. I have been attempting to convert these values into actual Boolean values, however, my current method always returns true. What is the correct a ...

A more effective method for restricting the properties of a field in an aggregate query

In my MongoDB query, I am attempting to use the aggregate function to fetch data from one collection while limiting the amount of data retrieved from another collection. Here is the code snippet that I have come up with: getFamilyStats: function (req, res ...

Angular Transclude - ng-repeat fails to iterate over elements

Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below: <!DOCTYPE html> <html> <head> <title>Directive test</title> <script type="text/ja ...

Tips for generating cascading dropdown lists with AJAX

After using the code below, I encountered an issue with storing the value of the second dropdownlist in the database when clicking on the update button. An error occurred referring to a null value. In the form.aspx.cs file, I attempted to retrieve the valu ...