What is the best way to extract information from a JSON XHR request and incorporate it into my template?

I am brand new to using Ember. Right now, my main goal is to connect to an API that provides random text and then show that text on a webpage. The specific API endpoint I am using is "" which will give back a response in JSON format.

app/controllers/randomtext.js

import Ember from 'ember';

export default Ember.Controller.extend({
  ajax: Ember.inject.service(),
  actions: {
    sendRequest() {
      return this.get('ajax').request('http://www.randomtext.me/api/lorem/ul-5/5-15');
    }
  }
});    

The XHR request is successful, and the correct JSON object is being returned as I can verify in the Chrome developer tab.

This is my app/templates/randomtext.hbs

<h1>Random Text</h1>

 <p>test</p><button {{action "sendRequest"}}>testing</button>

Clicking the button triggers the xhr request successfully. However, I am unsure how to access the text_out property of the JSON response or display any part of it. Can someone provide a simple tutorial on how to make a GET request to an external API endpoint and showcase the response on a webpage within my ember application?

Answer №1

In your action handler, you are returning without rendering anything on the screen. To display content, you must establish a binding between your template and JavaScript file. Check out this example twiddle. I've added {{randomText}} in application.hbs, which connects to the randomText attribute in the application.js controller. Initially, it's undefined, so no text is shown. When you click the button, the action handler in application.js is triggered. Inside the handler, the data from a remote call is assigned to the randomText attribute using Ember.String.htmlSafe (which converts the string into HTML format). You can directly link attributes defined in the controller with the corresponding template. If you're using a route instead of a controller, you need to utilize the model hook. I recommend exploring the official Ember Guide and completing the tutorials provided there.

Answer №2

To send a request, navigate to the app/routes/randomtext.js file and access the model hook.

model: function() {
 Em.RSVP.Promise.cast(Em.$.getJSON('http://www.randomtext.me/api/lorem/ul-5/5-15')).then((function(_this) {
      return function(data) {
    return Em.Object.create(data);
  };
})(this));
}

setupController: function(controller, model) {
  this._super(controller, model);
 return controller.set('textData', model);
}

In the app/templates/randomtext.hbs file,

You can utilize the

{{#each textData as someText}} <li>This is first item in array {{someText.item}}</li> {{/each}}
helper for looping through an array. If the response is a simple object and you only need to display a specific property, use {{textData.title}}.

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

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

tips for transmitting JSON data via the PHP API

I have successfully sent a text push from the PHP API code, but I am now wondering how to send JSON data as well using the PHP API. The issue I'm facing is that when I send JSON from the PHP API code, it is received as a "message" type. Interestingl ...

Utilize PHP to filter JSON data and dynamically populate a dropdown menu with the results

In my PHP application, I have a JSON data set containing information about various users. I need to filter out the individuals with a status of Active and display them in a dropdown list. How can I achieve this? Below is the JSON data: [ { "usernam ...

Is anyone else experiencing issues with the Express middleware that checks for IDs? Looking for suggestions on how to fix

Currently working on a project with Node js utilizing Express and MongoDb for the backend. In this project, USERS have the ability to post COMMENTS, so I have created a middleware to access the DELETE route and check if the USER ID matches the ID of the in ...

Utilizing AJAX in Wordpress to Dynamically Update HREF Links

My website now has AJAX functionality, and you can see a live example at www.mathewhood.com. I am interested in changing the URL format when clicked from To something like , without the /sitefiles/ for security reasons. Below is my code. If anyone is ex ...

Issue: .catch(error) function in Node / Express not returning as expectedDescription: After

I'm currently developing a REST API and focusing on effectively managing all error scenarios. Upon successful completion of the API call, I make sure to return the success object to the calling function and then send the response to the client. Howev ...

Creating interactive navigation bar effects with scroll and click functionality using jQuery

Is there a way to make the navigation highlight when a user clicks on it and also scrolls to the corresponding section? Currently, I am facing an issue where only the third navigation event highlights, most likely because when navigating to the fourth or f ...

The information retrieved from the API is not appearing as expected within the Angular 9 ABP framework

I am facing an issue with populating data in my select control, which is located in the header child component. The data comes from an API, but for some reason, it is not displaying correctly. https://i.stack.imgur.com/6JMzn.png. ngOnInit() { thi ...

What could be causing the AngularUI bootstrap datepicker to not appear?

Exploring the popup datepicker demo from angularUI bootstrap, which is embedded in their page and works perfectly. However, when I tried to create a minimal plunker here, the button click does not open the calendar. Any thoughts on what might be causing th ...

What is the best way to extract data from a basic JSON response using a fetch request

I am encountering an issue with a simple JSON object in my fetch response. When I attempt to access it, the code gets caught in the catch block. this is my response { "islogin": true } fetch(url, data) .then(res => {console.log(res);retur ...

What is the best method for initializing the value of ng-model as an empty string in AngularJS?

I need help setting the initial value for an attribute in my model. Here's the code I'm using: <input type="text" ng-model="selectedModel.title" name="title" value="" > What I want is for the attribute value to be initially set as an empt ...

What could be causing the service method in the controller not to be called by Node JS?

In my current Node JS project, the folder structure of my app is as follows: src │ index.js # Main entry point for application └───config # Contains application environment variables and secrets └───controllers # Hou ...

Effortlessly query a MySQL database using Whoosh to generate real-time JSON search results

Seeking guidance on how to index a MySQL table with Whoosh and generate an instant search page displaying results in JSON format. Are there any existing scripts or projects that already accomplish this task? Have searched extensively but only come across H ...

UV mapping with Plane BufferGeometry in Three.js

I'm facing some challenges creating a buffergeometry plane, specifically with the uv coordinates. Despite following advice from Correct UV mapping Three.js, I can't seem to achieve the desired result. Below is the snippet of code for the uv coor ...

Having trouble with jQuery animate function?

I have been struggling to get my animate function to work, despite looking at multiple similar posts and making modifications to my code. My goal is to make an image of a plane move from left to right across the screen and stop halfway. Here is the code I ...

Is it possible to utilize PubNub for updating and removing messages without requiring the "Storage & Playback" feature?

I am in the process of creating a real-time CRUD application. My project involves a Rails backend integrated with AngularJS. The database being used is PostgreSQL, and Angular communicates with the backend through a JSON API. Currently, I have successfully ...

Encountering an issue of duplicate key error when using multiple v-for loops with various keys

I've encountered an issue while working on a Python application that utilizes Vue.js. A ticket came my way with an error message stating: [Vue warn]: Duplicate keys detected: ''. This may cause an update error. (found in Root) The pro ...

Learn the process of synchronously loading forms and data in Angular

Looking to synchronize the loading of data and form... Let's start by reviewing the code: ngOnInit() { if (this.data.fromCalendar) { this.singleTraining(); } }, 200); this.formControl(); } formControl() { this.gib ...

How can recursive addition of identical key value pairs be accomplished in JSON by using C#?

I've been experimenting with various approaches to achieve this goal, my input is: string statment = "(Entity.CIFNumber <> '3123' AND Entity.Country LIKE 'USA' AND (Entity.FYEMonth= 'May' OR Statement.ProgitBefore ...

What is the process for upgrading TypeScript to the latest version?

Is there a way to upgrade TypeScript version for ASP.net MV5 project in Visual Studio 2015? I attempted searching through Nuget but couldn't locate it. There seems to be an issue with the razor intellisense (index.d.ts file) and I'm hoping that ...