Having trouble fetching external JSON data in a template within EmberJS framework

Struggling with a problem in EmberJS and unable to find a solution despite trying various methods. I am diving deep into learning this, hence created an account to seek assistance :)

The issue lies in fetching JSON data from the route in EmberJS and displaying it in the template. Surprisingly, the data is displayed successfully through a JavaScript alert in the route.

My task involves utilizing a third-party API to extract WHOIS information for domains via http.

Provided below is a snippet of the example JSON output:

{
  "status": [
    "clientTransferProhibited https:\/\/icann.org\/epp#clientTransferProhibited"
  ],
  ...
}

Presenting my current code:

routes/file.js

import Ember from 'ember';

export default Ember.Route.extend({
  titleToken: "MyTitle",
  model() {
      $.ajax({
        type: "GET",
        url: "https://api.who.pm/apple.com",
        dataType: "json",
        success: function(jsonData) {
          alert(JSON.stringify(jsonData));
          return jsonData;
        },
        error: function(request, status, error) {
          console.log("Error! " + request.responseText);
        }
      });
      }
});

Despite numerous attempts in templates/file.hbs to display the jsonData, I haven't been successful. Tried variations like {{model}}, {{model.data}}, among others. The main goal right now is to showcase the data within the template itself.

The page triggers the alert successfully upon loading.

Any assistance on this matter would be highly valued. Thank you!

Answer №1

It is crucial that the model hook returns either a promise or tangible data; returning nothing will not suffice.

The return jsonData statement does not belong to the model hook, but rather signifies the success function. By the time the success function is executed, the model hook has already completed its task.

I would strongly advise you to delve into JavaScript functions, callbacks, and closures. Familiarize yourself with concepts like this and Promises as well.

If you are working with jQuery, keep in mind that jQuery 2.x's .ajax() method may return a thenable object, but it is not a genuine Promise. This issue has been addressed in jQuery 3.x. In the meantime, utilize RSVP.resolve:

model() {
  return Ember.RSVP.resolve($.ajax({
    type: "GET",
    url: "https://api.who.pm/apple.com",
    dataType: "json",
  }));
}

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

The particles-js effect only partially fills the page

I've encountered some issues with particles-js. Firstly, it fails to cover the entire page. Additionally, I seem to be unable to interact with the particles for reasons unknown. Here is the HTML code snippet: <script type="text/javascript" src="j ...

What role does the conditional statement play in the function ExtrudeGeometry.UVGenerator.generateSideWallUV within three.js?

Within three.js's ExtrudeGeometry.UVGenerator.generateSideWallUV function, there is a specific condition being checked: if ( Math.abs( a.y - b.y ) < 0.01 ) { return [ new Vector2( a.x, 1 - a.z ), new Vector2( b.x, ...

Tips for creating a reactive bot that responds to a particular message?

I attempted to create a custom command for my Discord bot that would allow it to react to specific messages, but unfortunately I seem to have made an error somewhere in the code. Can anyone help me figure out what went wrong? Below is the code snippet I u ...

Learn the simple process of resetting a form with the input type reset functionality

Hello! This is my first time asking a question here, so please bear with me if I make any mistakes. I am attempting to reset a form using the input type=reset tag in HTML5, but I'm encountering some issues. I've included a snippet of my code bel ...

Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent it. <template> <div> <input type="number" v-model="a" style="color: white" /> <input type="number" v- ...

Deactivate the second dropdown menu until the first one has been filled with options

Can someone help me with greying out the second jump box (Select a Subcategory) until a valid selection is made in the first one (Choose a Category)? Below is the current code. Thanks! <script type="text/javascript"> \$j(document).ready(fu ...

Incorporating unique symbols into a RegExp object during its creation using a variable

As a beginner, I am currently working on a small function that will allow users to pick up objects and add them to an inventory by entering text in a box. In my setup, there is a text box with the id "commandBox" and a button that triggers the 'pickU ...

Show the content retrieved from the JSON post request

In the javascript code below, I am trying to delete a page using $.post() and then display a message with showStatus(). Instead of hardcoding the message in showStatus(), I want to pass the text returned by the $.post() call. How can I achieve this? $.p ...

Execute a PUT request within a Firebase Cloud Function database handler

I am working on syncing data between my server's database and Firebase realtime db. The first part, which involves syncing from my server to Firebase, is already complete. However, I am facing challenges with the second part - syncing data from Fireba ...

Error in translation: Some parts of JavaScript code are not functioning properly in Django

Check out this snippet of code: var text = `<div id='weather_data'> <img id='weather_icon' src='${weather_icon}'> <span id='centered'>${data[0].temperature}°c</span> ...

The animated loading image is taking an eternity to actually load

My website is loaded with heavy front-end features and I'm using a loading gif to help with the loading process. However, I've noticed that in Safari, there is a delay before the gif loads after the background does, which takes away from the inte ...

Steps for creating a functional dropdown menu using list items and retrieving the selected values

I am looking to implement a feature with multiple drop-down menus using list items. The functionality I desire is that when the user clicks on a ul element, the list items should drop down. Then, upon clicking on a specific list item, the value of that ite ...

Updating specific fields when using Put method with Restify and SQLite3

I am currently utilizing Restify alongside a SQLite3 database. Here is what I have implemented for my put method: server.put('/users/:userid', function(req, res, next) { bcrypt.hash(req.body.password, 10, function(err, hash) { if (err) { ...

Encountering a JSON parse error while attempting to install the Express package via package

Hey there! I'm currently in the process of installing Express via npm, but I encountered some error messages along the way: npm ERR! file C:\Projects\node\package.json npm ERR! code EJSONPARSE npm ERR! Failed to parse JSON npm ERR! Une ...

Comparison Between Angular 4 `ng serve --prod` and `ng serve` Commands

So, here's the situation: I have an app that is 4.6MB when running on ng serve. When I run: ng serve --prod The file size drops to 1MB. However, when I use --prod, my entire application breaks. All of my services (which are promise-based) that ...

Creating a Loop with JavaScript through a List

My current API response format is: "imagePath": "path1", Here is the JavaScript code I am using: <div className="flexAlignCenterJustifyCenter"> {event.imagePath ? ( <img src={event.imagePath} onErro ...

The issue with object alignment in the camera rotation is not properly centered in the Three.js framework

After bending two meshes into a circle to create a 3D marquee, I'm facing issues with centering them to the camera. For the full code, please visit https://jsfiddle.net/siiiick/1jh49e1u/ var text = "EXPRESS FREE SHIPPING WORLDWIDE OVER 200€ / ...

Issue with styling of ActionLinks and regular anchor links in MVC due to their small size

I recently encountered an issue that I couldn't resolve using an ActionLink, so I had to resort to using a regular hyperlink. Both links are styled similarly on the page due to passing the same css conditions, but I observed two key differences betwe ...

The Typescript compiler will continue to generate JavaScript code even if there are compilation errors

As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts: class Monster { constructor(name, initialPosition) { this.name = name; this.initialPosition = initialPosition ...

Components in Vue are not reflecting changes to reactive properties when using composition

I'm currently in the process of developing a notification system, and while it's partially functional, there are some issues. Here is the Composition function I am using: const data = reactive({ notifications: [] }); let notificationKey = 0; ...