What is the best way to display the JSON data?

<!DOCTYPE HTML>
<html>
<head>
<title></title>
    <link href="/bundles/hoaxpartner/css/style.css" type="text/css" rel="stylesheet" />
</head>
    <body>

    <div id="header">Backbone</div>
    <div id="sidebar"></div>
    <div id="content"></div>

    <script type="text/template" id="tpl-user-list-item">
        <a href='#users/<%= id %>'><%= name %></a>
    </script>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>

    <script>

        window.User = Backbone.Model.extend();

        window.UserCollection = Backbone.Collection.extend({
            model: User,
            url: "/app_dev.php/api/users/1/",
            parse : function(resp) {
                /*
                $.each(resp.users, function(key1, value1) {
                    resp.users[key1] = $.map(value1, function(value2, key2) { 
                        return [value2];
                    });
                });
                */
                return resp.users;
            },
        });

        // Views
        window.UserListView = Backbone.View.extend({

            tagName:'ul',

            initialize:function () {
                this.model.bind("reset", this.render, this);
            },

            render:function (eventName) {
                _.each(this.model.models, function (user) {
                    $(this.el).append(new UserListItemView({model:user}).render().el);
                }, this);
                return this;
            }

        });

        window.UserListItemView = Backbone.View.extend({

            tagName:"li",

            template:_.template($('#tpl-user-list-item').html()),

            render:function (eventName) {
                $(this.el).html(this.template(this.model.toJSON()));
                return this;
            }

        });

        // Router
        var AppRouter = Backbone.Router.extend({

            routes:{
                "":"list"
            },

            list:function () {
                this.userList = new UserCollection();
                this.userListView = new UserListView({model:this.userList});
                this.userList.fetch();
                $('#sidebar').html(this.userListView.render().el);
            }

        });

        $(function() {
            var app = new AppRouter();
            Backbone.history.start();
        });

    </script>

</body>
</html>

/app_dev.php/api/users/1 call output:

{
  "users": [
    {
      "userid": "Jf9CEy70",
      "password": "g5JY9OB2",
      "status_id": 1,
      "created": "2014-01-13 18:33:25"
    },
    {
      "userid": "8LZVQX6b",
      "password": "QFzO92tM",
      "status_id": 1,
      "created": "2014-01-13 18:35:00"
    },
    {
      "userid": "cItWduq9",
      "password": "SuzcWisl",
      "status_id": 0,
      "created": "2014-01-13 18:35:21"
    }
  ]
}

I am currently receiving the data from the API endpoint "/app_dev.php/api/users/1," but I am facing difficulties in displaying it.

Answer №1

Due to the asynchronous nature of this.collection.fetch();, calling it in the initialize method followed immediately by a call to index will result in the collection not being fully "fetched" at that time. It is essential to adjust your code to handle asynchronous calls correctly.

Furthermore, make sure you are listening for the correct event. Instead of using the change event, consider using the reset event (for resetting the model after fetching) or possibly the sync event.

Additionally, consider utilizing the request event, which triggers as soon as the ajax request is sent.

Revised: Thus, you can update

this.collection.on('change', this.render, this);

to

this.collection.on('sync', this.render, this);

Also, make sure to move

this.collection.fetch();

To be placed after

view = new App.Views.ModelsIndex({'collection' : this.collection});

Answer №2

1- Make sure to include the following function in your collection :

parse : function(resp) {
    return resp.users;
}

Your collection expects an array of models, but is receiving an object instead.

2- Replace this line

this.collection.on('change', this.render, this);
with
this.collection.on('reset', this.render, this);
, as the collection triggers a reset event when it receives data from the server (not change like the Model).

3- Insert this line

this.collection = new App.Collections.Models();

before this line

view = new App.Views.ModelsIndex({'collection': this.collection});

This is necessary because you are using this.collection without initializing it first.

4- Modify the tagName in your App.Views.ModelsIndex to el and specify the div where you want the template to be displayed ('#someEl')

UPDATE

The issue now lies in the template, there are errors present (userId instead of id, no name in your JSON), here is a corrected version:

<script type="text/template" id="tpl-user-list-item">
    <a href = '#users/<%= userid %>' ><%= created %></a>
</script>

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

Ways to access a function variable within an AJAX `done` function

This is the JavaScript function I am working with: $('.editable').change(function () { event.preventDefault(); var el_text = this.lastElementChild; var action = this.action; var method = this.method; var data = $(this).serialize(); ...

Pass the JavaScript variable to the Laravel controller for updating VueJS

Trying to send data from my modal to a controller to update data, but I'm not sure how to declare my variable and how to send this variable... Here is my current code: Vue.js <script> export default { data() { return { ...

From JSON tree structure to Oracle database tables

Within a CLOB, I have stored a JSON object that outlines a hierarchy: { "Version": 1, "nodes": [{ "id": 0, "Fields": ["ABC"], "nodes": [{ "id": 1, "Fields": ["DEF"], ...

Automatically install modules during the execution of the Node Webkit build process

After developing a Node Webkit application, I used NW-Builder to generate the run files. The app's size ended up being quite large at 200MB due to the numerous modules utilized. My question is whether it is feasible to create an installer that will f ...

Tips for successfully including a variable in a JSON string within a bash script

Below is a script that retrieves command output from a host and saves it to a file /tmp/${stcl}_aggr.txt. The content of this file is then stored in a variable body=$(cat /tmp/${stcl}_aggr.txt). When I try to use the Variable body in a JSON array as " ...

When the next button is clicked, the button content disappears

I am struggling with a problem involving two buttons that store tables. The issue is, I want the table to disappear when the second button is clicked and show the contents of the second button immediately after clicking it once, rather than having to click ...

When using Angular's ng-repeat with a JSON data source retrieved through $http AJAX, the resulting list

My goal is to showcase a list of elements by name and id using ng-repeat from a JSON file with a very basic AJAX request. var form = $("#loadAllServiceEngineForm"); var url = form.attr("action"); var App = angular.module('AdamApp', ...

JavaScript Function Not Executed in Bottom Section

I've implemented AngularJS includes in my project. Below is the code snippet from my index.html: <!DOCTYPE html> <html ng-app=""> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> ...

The user interface does not get refreshed right away; it only shows the changes after the

Here is an example of HTML: <div ng-repeat="user in controller.users"> <p>{{user.name}}</p> <button ng-click="controller.deleteUser(user)" value="delete"></button> </div> Next, we have the controller code: vm ...

Developing HTML5 animation by utilizing sprite sheets

Struggling to create an engaging canvas animation with the image provided in the link below. Please take a look at https://i.stack.imgur.com/Pv2sI.jpg I'm attempting to run this sprite sheet image for a normal animation, but unfortunately, I seem to ...

Transmitting a JSON object through an HTTP POST request on an Android device

This is not a duplicate. The provided link is outdated as "http client" has been removed in api23. I am attempting to send a JSON object: {"emailId":"example@example.com","address":"Naya bans","city":"Noida","pincode":"201301","account_number":"911235463 ...

Tips for preserving drop down selections when refreshing the page

I am currently working on a program with 2 drop-down menus and 2 buttons. My goal is to have the first button disabled and second enabled when both dropdowns are selected and the "start" button is clicked. Additionally, I want the dropdowns to be disabled ...

Ensure that all content in the table rows remains visible, even in a table with unusually lengthy cells

My HTML table is structured like this: +-------------+-------------+----------+ | Single line | Single line | Very, | | | | very | | | | long | | | | text, | | ...

As the user types, the DD/MM/YYYY format will automatically be recognized in the

In my React component, I have an input box meant for entering a date of birth. The requirement is to automatically insert a / after each relevant section, like 30/03/2017 I am looking for something similar to this concept, but for date of birth instead of ...

Ways to resolve a blank outcome in the $scope selection choices list?

Currently, I am utilizing AngularJS to create a select dropdown field populated with options from an array. The end user has the ability to add options via an input box. While the $scope successfully adds to the array, the dropdown select box displays "und ...

Dynamically fill the tabs and their corresponding forms with data

When extracting data from the server, I am tasked with creating tabs and populating them with corresponding data. For example, if my data includes fields 'x' and 'y', I must generate two tabs (with identical form panels) and fill them w ...

The tab key seems to be malfunctioning when triggered during a jquery change event

I encountered an unusual issue with my jQuery events, and I'm not entirely sure if it's a problem related to jQuery. In hopes that some jQuery experts can shed some light on this. The code snippet below was included in my HTML page to automatica ...

The issue with CKEDITOR is that it fails to send data through ajax upon the initial submission

When using CKEDITOR, I am experiencing an issue where my forms do not send data to the server on the first submit. If I click the submit button once, empty fields are sent without any input from me. However, when I submit the form a second time, only then ...

Error status code encountered while attempting to send email

Even after reading through this, I'm still unsure about how to correctly build the email sending function. So, I have a question: What HTTP status code should be used when an email fails or succeeds during the sending process? In my Rails app, a POST ...

I have successfully implemented the Context API in my Next.js project and everything is functioning smoothly. However, I encountered an error while using TypeScript

Currently, I am working on a Next.js project that involves using the Context API. The data fetched from the Context API works perfectly fine, but I am encountering errors with TypeScript and I'm not sure how to resolve them. Error: Property openDialo ...