Knockout failed to display the template using the provided data

Having difficulty with JavaScript's knockout library. I am trying to create a simple forum. I have a JavaScript file with two AJAX requests, one for topics and the other for posts. I also have an HTML template.

function dealModel() {
  var self = this;
  self.board = ko.observableArray([]);
  var res = [];

  $.getJSON("http://someaddress/threads", function(data) {
    $.each(data, function(i, thread) {
      var js = jQuery.parseJSON(thread);
      js.posts = ko.observableArray([]);
      var postres = []
      $.getJSON("http://someadress/posts/" + js.id, function(postdata) {
        $.each(postdata, function(idx, post){
          var jspost = jQuery.parseJSON(post);
          postres.push(jspost);
        })
      })

      js.posts(postres);
      res.push(js);
    })

    self.board(res);
  })
}
$(document).ready(function(){
  ko.applyBindings(new dealModel());
});
var testdata = [{text : "text 1"} , {text : "text2"}]

This is my JavaScript code. It works perfectly with topics, but when I try to add posts, my observable array "posts" ends up empty. For testing purposes, I created a test array "testdata" (mentioned below), and passed it to my observable array. The JavaScript worked perfectly in that case. Here is my template:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>

<script type="text/javascript" src="ajaxknockout.js"></script>
</head>
 <body>
    <div class='board'>
  <div class='threads' data-bind="foreach: board">

  <p data-bind="text: title"></p>

  <div  class= "posts" data-bind="foreach: $data.posts">

    <p data-bind="text: text"> </p>
    </div>
  </div>


</div>
 </body>>
</html>

I suspect there may be an issue with how my posts JSON is structured. Here is what the production data looks like:

["{\"createTime\": \"Monday, 04. January 2016 05:53PM\",\"thread_id\": \"2\",\"text\": \"post 1\",\"id\": \"4\"}", "{\"createTime\": \"Monday, 04. January 2016 05:53PM\",\"thread_id\": \"2\",\"text\": \"post 2\",\"id\": \"5\"}", "{\"createTime\": \"Monday, 04. January 2016 05:53PM\",\"thread_id\": \"2\",\"text\": \"post 3\",\"id\": \"6\"}"]

Therefore, I have a question. What could be wrong with my code? Why does knockout accept my testdata but completely reject the production data?

Answer №1

It seems that the issue lies in the timing of your json requests. The code snippet below shows where the problem may be:

js.posts(postres);

The above code is executed before the callback from your second json request, which fetches posts data. To resolve this issue, you need to ensure that the posts array is populated before calling js.posts(postres);. You can achieve this by adjusting your code as follows:

$.getJSON("http://someadress/posts/" + js.id, function(postdata) {
    $.each(postdata, function(idx, post){
        var jspost = jQuery.parseJSON(post);
        postres.push(jspost);
    })
    js.posts(postres);
})

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

Sending JSON data from PHP to JavaScript using Ajax

Currently, I am attempting to transfer a JSON object from a PHP script to a JavaScript file using Ajax. The code I have been using successfully for a single string is now being modified to accommodate multiple strings within a JSON object. Below are snippe ...

What is the best way to retrieve JSON elements and store them in lists?

I have a JSON list of objects that looks like this: "server-1": { "username": "admin542", "on_break": false, "scheduling_type": 1, "schedule": { "Monday": [ ...

Javascript Error: Object Expected

Recently, I have encountered an error in my code that says "object expected" in JavaScript. Surprisingly, the code was working perfectly fine before this issue arose. Strangely, the code is still functioning properly in another solution. Even after making ...

The jQuery .hasClass() function does not work properly with SVG elements

I am working with a group of SVG elements that are assigned the classes node and link. My goal is to determine whether an element contains either the node or link class when hovering over any of the SVG components. However, I am encountering an issue where ...

What happens when an AJAX request doesn't have a success field?

Is it possible to execute an ajax call without specifying a success function? $.ajax({ type: "POST", url: "/project/test/auto", data: data, // no success function defined here }); My reasoning for this is that I have PHP code that insert ...

The concept of accessing a reference in JavaScript

Take a look at this code snippet: http://jsfiddle.net/GKBfL/ I have a function called collection.prototype.add and I want it to return a reference so that the final alert will show testing, testing, 123, testing. Any ideas on how to achieve this? Here i ...

In React, the functionality of rendering components conditionally is not functioning properly

I am looking to conditionally display either the Login component or Menubar component based on the value of the isLogin state. If the isLogin state is false, I want to render the login page. If it is true, I want to render the Menubar page. To achieve thi ...

Enhance User Experience by Updating Status on Checkbox Selection in PHP

I am working with a datatable and I have created a table using datatables. How can I change the status field when a checkbox is clicked? The default status is 'before', but when the checkbox is clicked, it should update to 'after' in th ...

Exploring the mechanics of an Ajax call

Feeling a little lost in the call flow of Ajax - can anyone provide some guidance? This is my HTML: <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="myFunction()">Change Content</but ...

Require assistance with try-catch statements

I am troubleshooting an issue with a try-catch block in my Protractor test. Take a look at the code snippet below: try { element(by.id('usernameas')).sendKeys(data); } catch(err) { console.log('error occurred'); } To test the ...

The element will only show up upon resizing (in Safari web browser)

I am facing a problem with a button styled using the class btn-getInfo-Ok <button class="btn-getInfo-Ok">Hello</button> in my style.css file .btn-getInfo-Ok { color:white !important; margin: 0 auto !important; height:50px; bottom:0; ...

Using BeautifulSoup to search for XML elements with the find_next method while specifying a single attribute to limit

Any assistance would be greatly appreciated! I am encountering an issue with the output generated from the XML file example provided below. Incorrect output: Emp_F_Name: Jill Emp_M_Name: H Emp_L_Name: Jones Desired output: Emp_F_Name: Jill Emp_M_Name: No ...

The outcome varies between PHP Local Host and server environments

I have developed a script for searching lk domains. Below is the code: <form action="" method="GET"> <input type="text" name="dm" placeholder="Enter Domain Name"> </form> <?php if (isset($_GET["dm"])) { $domain = $_GET["dm ...

Identification of absence of file selected in input file control

Imagine a scenario where I need to select an image to display on the screen from a select control. If the desired image is not available, I want to be able to choose it from the disk and add this option to the select control while automatically selecting i ...

Keep your data safe and protected within a Node CLI application

Currently developing a NodeJS command-line application that interacts with an API to provide data to users. To access the public API, users need an API token. The CLI will be globally installed on users' machines using npm i -g super-cool-api-cli. Up ...

Tips for parsing deeply nested JSON results in multiple levels

Screenshot from Firebug in Chrome Recently, I've been encountering challenges with parsing multi-level nested JSON objects. I'm currently working on a real estate website that receives data from a third party in JSON format. However, the data is ...

Searching through text in Node JS using Mongoose for Full-Text queries

I am facing an issue while attempting to perform a full-text search on an array of strings using Mongoose. The error message I receive is as follows: { [MongoError: text index required for $text query] name: 'MongoError', message: 'text ...

Guide to handling multiple forms within a single template using Express

If I have an index.html file containing two tables - "Customers" and "Items", along with two forms labeled "Add customer" and "Add item", how can I ensure that submitting these forms results in a new entry being added to the respective table as well as t ...

What methods can I use to analyze the integrity of the data's structure?

Currently working on an API using NestJS and typeorm. I am in need of a way to verify the format of the data being returned to clients who make requests to it. For instance, when accessing the /players route, I expect the data to have a specific structure ...

React Highchart issue: The synchronized chart and tooltip are failing to highlight the data points

I am currently utilizing the highchart-react-official library to create two types of charts: 1) Line chart with multiple series 2) Column Chart. My objective is to implement a synchronized behavior where hovering over a point in the first line chart hig ...