Displaying data stored in a database using JSON format with Ember

I seem to be facing a challenge once again. Let me elaborate on what I am trying to achieve.

Within the teammembers template, I aim to display information about Team Members and their details from a specific team by joining 3 tables.

Here is an example of the query:

SELECT * 
FROM teams_members tm
inner join members m on tm.members_member_id=m.id
inner join teams t on tm.team_team_id=t.id
WHERE 
t.team_name='Vancouver Canuck'

Initially, I thought I could create a simple array and use pushObject. However, this approach is not working and I'm unsure of how to display the information.

Here is what I have attempted:

App.Model = Ember.Object.extend({});

App.TeammembersController = Ember.ObjectController.extend({
    teammembers : [], //This is for the getTeamMembers Action, coming up as undefined 
    selectedTeam : null,
    team : function() {
        var teams = [];
        $.ajax({
            type : "GET",
            url : "http://pioneerdev.us/users/getTeamNames",
            success : function(data) {
                for (var i = 0; i < data.teams.length; i++) {
                    var teamNames = data.teams[i];
                    teams.pushObject(teamNames);
                }
            }
        });
        return teams;
    }.property(),

    actions : {
        getTeamMembers : function() {

            teamName = this.get('selectedTeam.team_name');
            data = {
                team_name : this.get('selectedTeam.team_name'),
            };
            if (!Ember.isEmpty(teamName)) {

                $.ajax({
                    type : "POST",
                    url : "http://pioneerdev.us/users/getTeamMembers",
                    data : data,
                    dataType : "json",
                    success : function(data) {
                        for (var i = 0; i < data.teammembers.length; i++) {
                            var teamNames = data.teammembers[i].firstname;
                            teammembers.pushObject(teamNames);
                        }
                    }
                });
                return teammembers;
                console.log(teammembers);
            } else {

            }

        }
    }
});

I am encountering an issue where the teammember array is undefined in this scenario. The snippet within the actions will be responsible for displaying Team Member information when a Team Name is selected from Ember.Select.

I would like to give credit to for guiding me to reuse my snippet in this context:

<script type="text/x-handlebars" id="teammembers">
            <div class="row">
                <div class="span4">
                <h4>Your Team Members</h4>
                {{view Ember.Select
                contentBinding="team"
                optionValuePath="content.team_name"
                optionLabelPath="content.team_name"
                selectionBinding="selectedTeam"
                prompt="Please Select a Team"}}
                <button class="btn"
                {{action 'getTeamMembers' bubbles=false }}>Get Team Members</button>
                </div>
            </div>
        </script>

Furthermore, the user will select a team from Ember.Select and upon clicking the button, I should be able to display the team members and their information somewhere. In the future, I might want to retrieve IDs and delete them from the server as well. How can I accomplish this?

Therefore, should I implement custom views or is there an alternative approach to address this?

Answer №1

There seems to be a problem with the code that fetches properties using ajax calls. Specifically, the code for the team property of App.TeammembersController is not handling the data properly.

First, it initializes a local array variable called teams.

Next, it uses ajax to retrieve the data from the server asynchronously.

However, within the ajax callback, the teams array is populated but not returned in the correct state with the data. It is crucial to set the controller's property after the teams array has been filled with the data. This way, ember's binding will automatically update the controller's property and notify any other interested objects, including the template for rendering the results.

Finally, it returns an empty teams array.

To address this issue, you should add the following two lines of code:

team : function() {
        var teams = [];
        var self = this;
        $.ajax({
            type : "GET",
            url : "http://pioneerdev.us/users/getTeamNames",
            success : function(data) {
                for (var i = 0; i < data.teams.length; i++) {
                    var teamNames = data.teams[i];
                    teams.pushObject(teamNames);
                }
                self.set("team",teams);
            }
        });
        return teams;
}.property()

The same approach should be followed for retrieving other properties from ajax calls.

EDIT1

Below is an example based on your code. The code has been moved into the IndexController and the button action has been disabled for simplicity.

HBS

<script type="text/x-handlebars" data-template-name="index">
  <div class="row">
                <div class="span4">
                <h4>Your Team Members</h4>
                {{view Ember.Select
                content=teams
                optionValuePath="content.team_name"
                optionLabelPath="content.team_name"
                selection=selectedTeam
                prompt="Please Select a Team"}}
                <button class="btn"
                {{action 'getTeamMembers' bubbles=false }} disabled>Get Team Members</button>
                </div>
            </div>

            selected team:{{selectedTeam.team_name}}
  </script>

JS

App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});


App.Model = Ember.Object.extend({});

App.IndexController = Ember.ObjectController.extend({
  test:"lalal",
    teammembers : [],
    selectedTeam : null,
    teams : function() {
        var self = this;
        setTimeout(function(){
            var data = [{team_name:'team1'}, {team_name:'team2'}, {team_name:'team3'}];
            self.set("teams",data);
        },1000);
        return [];
    }.property(),
    actions : {
        getTeamMembers : function() {
            teamName = this.get('selectedTeam.team_name');
            data = {
                team_name : this.get('selectedTeam.team_name')
            };
            if (!Ember.isEmpty(teamName)) {
                return teammembers;
            } else {

            }

        }
    }
});

Remember that all requests are asynchronous, so make sure to update your ember app model/data within the callback functions to leverage ember bindings effectively.

EDIT2

If you want to display team members in a separate view once a team is selected, you can make an ajax call to fetch the members for the selected team id. You can render the teammembers property using a view or partial. Here is an example:

HBS

<script type="text/x-handlebars" data-template-name="_members">
  <i>this is a partial for members</i>
  {{#each member in teammembers}}<br/>
  {{member.firstName}}
  {{/each}}
  </script>

JS

App.IndexController = Ember.ObjectController.extend({
  test:"lalal",
    teammembers : [],
    selectedTeam : null,
    teams : function() {
      var self = this;
      setTimeout(function(){
          var data = [{team_name:'team1'}, {team_name:'team2'}, {team_name:'team3'}];
          self.set("teams",data);
      },1000);

        return [];
    }.property(),
    actions : {
        getTeamMembers : function() {
  var self = this;
  setTimeout(function(){
          var data = [{firstName:'member1'}, {firstName:'member2'}];
    self.set("teammembers",data);
    },1000);

        }
    }
});

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

Is there a way to extract the HTML source code of a website using jQuery or JavaScript similar to PHP's file_get_contents function?

Can this be achieved without a server? $.get("http://xxxxx.com", function (data) { alert(data); }); I have tried the above code but it seems to not display any output. ...

Can you incorporate personalized icons in ReactJS?

Is there a way to incorporate my personally designed custom icons, available in both SVG and TTF formats, into a React project? I am interested in using these icons in my navigation bar, such as creating a unique home icon for the home button. ...

Locate the syntax mistake within a JSON structure

It's been a whole hour and I'm still searching for that elusive syntax error in the JSON data! I can't share the entire code, so I've uploaded it to GoogleDocs instead View Json.data here ...

Adjusting webpage background with JavaScript

I've been struggling with this for the past six hours and can't seem to get it right. I've checked out various solutions on Stack Overflow, but nothing seems to work. What am I missing here?!? My html5 page doesn't have a background an ...

Tips for utilizing a static constant within a class's .h file to specify the size of an array

Looking for a way to work around some coding constraints in C++03. Here's the scenario within a .h file : namespace myNamespace { class MyClass { protected: MyArrayType myArray[10]; }; } The constraints are as follows ...

Exploring the process of transferring a variable from Frontend to Backend via a GET API in ReactJS with an Express API

When working with my freight Shipment table, I need to access the email of the logged-in user in order to perform some frontend tasks. However, I am struggling to retrieve this information using the Axios.get() method and use it to query my MySQL DB. In t ...

Adding new options to a multi-select dropdown in Vue.js when fetching data using an

Greetings! I've been utilizing a modified wrapper to manage a multiple select for vue.js. My goal is to change the value of 'this' inside the vue component. Below is the snippet of my code. <select2-multiple :options="car_options" v-mode ...

Encountered a CSV Parse Error while using the npm package csvtojson: Error: unclosed_quote

NodeJS version: v10.19.0 Npm version: 6.13.4 Npm package csvtojson Package Link csvtojson({ "delimiter": ";", "fork": true }) .fromStream(fileReadStream) .subscribe((dataObj) => { console.log(dataObj); }, (err) => { console.error(err); }, (suc ...

Unsure why my React component isn't triggering a re-render?

I encountered an issue when trying to update my component based on a state change. When I update the state outside of an HTTP call, the component updates correctly. However, when I try to do the same inside an HTTP get call, the state is updated but the ...

Close any other panel when one is selected in a loop

I am experiencing difficulty with a series of menus that are causing other panels to hide when one is clicked and active. @{int i = 0;} @foreach (var levelOne in Model.MenuLevelOne) { <div class="panel-group" id="accordio ...

Can you provide guidance on decompressing SVGZ files using JavaScript?

I'm currently working on implementing a high-resolution world map using SVGZ instead of the standard SVG format, aiming to provide my users with a more intricate and detailed visualization. Although I have experimented with utilizing js-deflate to de ...

When clicking the button in ASP.NET MVC 5, the model is not defined

I have been struggling with an issue where a dropdownlist in a partial view, loaded via ajax into another view, is causing the Model to be null when trying to select an option and click a button. Despite the Model being populated for the dropdown, an error ...

What is preferable: defining JSON schema properties or utilizing oneOf conditions within an array of objects

I am looking to represent a variety of objects in a schema through an array called contents. This array can include any number of elements, but they must fall into one of two categories: one type represents text while the other type represents images. Up ...

An unforeseen issue occurred while trying to access an indexed element ID

I've recently started learning javascript and jquery, and encountered a problem while working on a script. The script is created by php code that reads lines from a file, processes them, and displays them using arrays. In addition, javascript validat ...

summoning the iframe from a separate window

In my current setup, I have a link that passes a source to an iframe: <a href='new.mp4' target='showVideo'></a> <iframe src='sample.jpg' name='showVideo' ></iframe> However, what I would lik ...

Learn how to incorporate an input field into a form using the same class name

I am facing a challenging JavaScript issue that I have been struggling to resolve. My predicament involves a dynamically formed table with form fields. Here is the code snippet in question: var table = document.getElementById("table"); var row = table. ...

Storing the information filled out in the form and utilizing it to navigate to the correct destination URL

With the generous assistance and insightful advice from members of Stack Overflow, I am nearing completion of my quiz project. However, I do have a few lingering questions regarding some final touches needed for the project. Before delving into those quest ...

What is the best way to remove all files, such as JSON files and images, that are included with the iOS app when updating

My iOS application includes some JSON files in its bundle. I recently updated these files and uploaded the new version to the app store. However, even after updating, the old data from the JSON files still appears. The only solution I have found so far is ...

Samsung S4 Android device experiencing interruption in HTML5 video playback

When using Android Webview to play html5 videos, including Youtube videos (using my own tags and Youtube embedded iFrames), I came across an issue with the Samsung Galaxy S4. The problem occurs in the following scenario: Play a video. Press 'back&ap ...

Sending a JSON object to an ASP.NET server

I have been attempting to send JSON data to my ASP.NET server on localhost. Initially, I tried posting the code to the master page but encountered a "Error 403: Forbidden" message. Subsequently, I attempted using a web service instead, which led to a myria ...