Having trouble with processing the binding? Use ko.mapping.fromJS to push JSON data into an ObservableArray

Hey everyone, I'm struggling with my code and could really use some help. I'm new to knockout and encountering an issue. Initially, I receive JSON data from the database and it works fine. However, when I click 'Add some', I'm trying to push the same data from the database to my observable array, but the code below isn't working. Any suggestions would be appreciated. Error: Unable to process binding "text: function (){return AdId }"...

HTML:

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

<div data-bind="click: addSome">Add some</div>

MODEL:

function AdListModel() {
var self = this;
self.Ads = ko.mapping.fromJS([]);

self.result = function (model) {
    ko.mapping.fromJS(model, self.Ads);
}    

self.InitialData = function () {
    $.ajax({
        type: "GET",
        url: '/Home/GetAllAds',
        data: { startPosition: 0, numberOfItems: 2 },
        dataType: "json",
        success: function (data) {

            self.result(data); <---- works

        }
    });
}

self.addSome = function () {
    $.ajax({
        type: "GET",
        url: '/Home/GetAllAds',
        data: { startPosition: 0, numberOfItems: 2 },
        dataType: "json",
        success: function (data) {

            self.Ads.push(data); <---- doesn't work

        },
    });

};

self.InitialData();
}

ko.applyBindings(new AdListModel());

I've already tried using

self.Ads.push(ko.mapping.fromJS(data))
but unfortunately, it didn't solve the problem.

Answer №1

It appears that the error message is indicating that your model is missing an AdId property.

Could you please provide a JSON model dump from your API?

Update

Your Ads property should be set as ko.observableArray() instead of using ko.mapping.fromJS([]):

function AdListModel() {
    var self = this;
    self.Ads = ko.observableArray([]);

    self.result = function (model) {
        ko.mapping.fromJS(model, self.Ads);
    }    

Update 2

Remember to map the data before pushing it:

$.ajax({
    type: "GET",
    url: '/Home/GetAllAds',
    data: { startPosition: 0, numberOfItems: 2 },
    dataType: "json",
    success: function (data) {
        self.Ads.push(ko.mapping.fromJS(data));
    },
});

Update 3

If your JSON data is in this format:

[
    {"AdId":1,"AdContent":"test1"},
    {"AdId":2,"AdContent":"test2"}
]

Then it is an Array and you must iterate over each entry:

$.ajax({
    type: "GET",
    url: '/Home/GetAllAds',
    data: { startPosition: 0, numberOfItems: 2 },
    dataType: "json",
    success: function (data) {
        data.forEach(function(d) {
            self.Ads.push(ko.mapping.fromJS(d));
        });
    },
});

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

Add navigation dots to the slider in order to align them with the specified div element

Visit this JSFiddle link for the code <html> <link href="./style.css" rel="stylesheet" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script&g ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data ...

managing the HTML class names and IDs for various functions such as styling, jQuery interactions, and Selenium automation

While there is an abundance of articles on writing clean HTML/CSS, one aspect that seems to be lacking advice is how to organize class names and IDs for different purposes such as design, jQuery, and Selenium testing. The challenge lies in deciphering the ...

Retrieve specific information using the identifier from the URL parameters during server-side rendering

I am trying to fetch data with a parameter from the URL using Nextjs. However, I am facing an issue where the parameter value is undefined. Here is the code snippet: const Room = () => { let fetchData; let roomId; const getID = () => { con ...

Utilize jQuery to extract data from a JSON object

While I have come across numerous examples of parsing JSON objects in jQuery using $.parseJSON and have grasped the concept, there are some fundamental aspects missing that are preventing me from successfully parsing the following VALID JSON: { "studen ...

Unexpected error in boot.ts file in Angular 2

I am currently experimenting with various folder arrangements for Angular 2. When attempting to launch a local server, I encounter the following error: Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/prod/app/TypeScript/bo ...

Utilizing Regular Input with Material-UI's Autocomplete Feature

Is there a way to replace TextField with a regular input in an Autocomplete? ...

What is the best way to ensure all requests have been completed before proceeding?

Is there a way to ensure that the sortOrder function only runs once the getOrders function has fully completed its execution? I have considered using a callback, but I am unsure of how to implement it. Do you have any suggestions on how I can achieve this ...

Guide on incorporating a thymeleaf custom dialect in an HTML script

Essentially, I am trying to create a dynamic schema using ld+json with thymeleaf. To fetch the URL for the corresponding page, we have set up a custom processor as shown below: public class CustomUrlAttributeTagProcessor extends AbstractAttributeTagProcess ...

Make the jQuery toggle() function work like a regular radio button when selecting multiple options at a time

I have recently created two radio buttons using <i> font icons. Previously, I had successfully used the same code to create a checkbox, so I applied it to the radio buttons as well. After fixing the positioning, everything seemed fine when interactin ...

Revitalize website when submitting in React.js

I need assistance with reloading my React.js page after clicking the submit button. The purpose of this is to update the displayed data by fetching new entries from the database. import React, {useEffect, useState} from 'react'; import axios from ...

Changing a Unique JSON Structure into a VB.NET Object

I have a JSON object that is structured as follows. { "Errors":{ "err1":[ //* Array of err1 objects ], "err2":[ //* Array of err2 objects ] } } This object is used to report errors identified in a request to a PHP page. My goal i ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...

Encountering a "self is not defined" error while utilizing the Jodti-React text editor within a Next.js project

Issue with 'self is not defined' error while using jodti-react in a Next.js project import React, { useState, useRef, useMemo } from "react"; import Dashborad from "./Dashborad"; import JoditEditor from "jodit-react" ...

Tips on maintaining a constant number of elements displayed within a container while scrolling using *ngFor

In an effort to improve the performance of loading a large amount of data inside a container div, I implemented a solution. It initially worked fine, but as I continued to append elements to the list while scrolling down, it started to slow down significan ...

Using Angular 6 to Format Dates

Can anyone provide instructions on how to achieve the following format in Angular? Expected: 20JAN2019 Currently, with the default Angular pipe, I am getting: 20/01/2019 when using {{slotEndDate | date:'dd/MM/yyyy'}} Do I need to write a ...

Using Rails to render a partial with jQuery for a loop function

I am trying to include a partial multiple times in my view with different parameters. I have a search form that returns project data in JSON format using Ajax. Now, I want to use a jQuery function to get the project and display it in the view. $.ajax({ ...

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...

Mastering MochaUI: A Comprehensive Guide

Can anyone direct me to a comprehensive tutorial for MoachaUI? I have a strong understanding of CSS, basic knowledge of JavaScript, and experience with PHP. The MoachaUI user interface has caught my interest, but I'm struggling to find a suitable lear ...