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

Is there a way to refresh CSS styles when the window width is adjusted?

Is there a way to refresh CSS styles when the window width changes? I attempted this method, but unfortunately it did not work as expected. A simple refresh (F5) helps to rectify the CSS tags. jQuery(function($){ var windowWidth = $(window).width(); ...

The dropdown selection for redirecting to a URL is malfunctioning within a PHP while loop

<?php $sql = "select * from letter where societyn='" . $_SESSION['socityname'] ."' "; $result = mysql_query($sql); $i=1; while($row=mysql_fetch_array($result)){ ?> <?php $id = $row['id']; ...

The JavaScript require() function appears to be malfunctioning

Why am I encountering an error when trying to import a valid node_module? <script > var Twit = require('twit'); </script> Error: Uncaught ReferenceError: require is not defined I am puzzled as to why the require() function wor ...

What is the best way to generate a new Object using an Object that contains Arrays?

I currently have a global array saved with a catalog and a list of items that the user has saved. My task is to generate a new array of Objects (with arrays) containing only the items saved by the user. I am working with javascript in react-native, and I ...

Attempting to eliminate an HTML element using JavaScript

Currently, I am working on creating an image rotator in JavaScript. The CSS fade animation I have applied only seems to work during element creation, so I am forced to remove the element on each loop iteration. The main issue I am encountering is related ...

Having issues with the jQuery toggle functionality

var resultsList = $("#test"); resultsList.text("Hello. This is jQuery!"); var tB = jQuery("#toggleButton"); tB.on("click", function() { resultsList.toggle(400); }); The syntax appears to be correct as there are no errors reported in the browser cons ...

Activate a Dropdown Menu by Clicking in a React Application

I have a collapsible feature where you can click to expand or collapse a dropdown. Currently, the dropdown can only be clicked on where the radio button is located. I want the entire area to be clickable so that users can choose the dropdown by clicking an ...

Identify if a process operates synchronously or asynchronously

Can you identify in node.js, with the help of a function, if a method is synchronous or asynchronous? I am interested in creating a function that achieves the following: function isSynchronous(methodName) { //check if the method is synchronous, then ...

Issue with undefined object in ExpressJS PUT method

Attempting to utilize the PUT method for updating a record in my database, I encountered an issue with the object not being defined. ReferenceError: blogpost is not defined Following this tutorial for routing steps, I noticed that while the variable is d ...

Enhancing Image Quality with jspdf and Html2Canvas

We are currently utilizing jsPDF and HTML2canvas to create PDFs, however, we have noticed that the image resolution is quite high. Is there a method available to obtain low-resolution images using jquery, javascript, jsPDF, and html2canvas? function addE ...

Ensure that data is not cached after the page is refreshed at regular intervals of x seconds

In the process of developing a news app, I have implemented a feature where a div with the class .new_feed is refreshed every 10 seconds to fetch new updates. However, I encountered an issue where if a new feed appears in the .new_feed div and is not cli ...

Exploring the functionality of allOf in JSON schema

I'm currently trying to understand the workings of the allOf keyword in JSON Schema. However, I'm having some trouble grasping its functionality. { "$schema": "https://json-schema.org/draft/2019-09/schema", "type" ...

Tips for incorporating an onClick event into a variable beyond the class extension

Currently utilizing React/Redux in this scenario. At the beginning of my code, outside of the class extends block, I have: const Question10 = () => (<div> <p>Insert question here</p> <input place ...

Looking for a way to streamline data transfer using script setup in Vue 3? Consider utilizing composables to simplify the process

In the scenario where there is a parent component labeled as "1" with two child components named "2" and "3", each of these components containing its own child component, "4" for "2" and "5" for "3", the challenge arises on how to pass state from child c ...

Obtaining a file from the Firebase database

After successfully implementing the login functionality in my app, I am now attempting to retrieve the user's document in order to display their name on the page. email = loginemail.value; password = loginpassword.value; signInWithEmailAndPass ...

Is onMouseLeave failing to trigger upon exiting an element?

Having an issue with the onMouseLeave event in React. It seems to be triggering when hovering over other elements like the navbar or console, but not when leaving the intended element. function GameCard({name, about, image}) { const [active, ...

Deleting an element from a JavaScript array

I have a collection of javascript functions that manage intervals by setting and clearing them. The intervals are stored in an array called intervals[]. config: { settings: { timezone: 'Australia/Perth,', base_url: location.p ...

I am utilizing jQuery's AJAX function with a datatype of HTML to extract a specific portion of the incoming data

This is the JavaScript function I am working with: function getCountryRegions() { var postData = "id="+$("#selectedCountryId").val(); $.ajax({ url:"/region", data: postData, dataType:"html", type:"POST", ...

Having trouble retrieving the array index of JSON data in Vue JS?

I have a project that includes data from a JSON API and I'm trying to display the index of each data. For example, I can view the floors from array index 0 to 22, but I'm having trouble getting the array index for the flats on each floor. Each fl ...

Experience the potential of HTML5 by playing dual audio MKV/AVI videos

After conducting some research, it seems that Chrome has the necessary codecs to play MKV videos. However, I have yet to come across any information on how to select audio tracks in MKV and AVI files using Javascript/HTML5. Does anyone have any insight in ...