Refreshing a knockout observable following an asynchronous AJAX request by utilizing ko.mapping.fromJS

I am encountering an issue with updating data on the UI after making an asynchronous call to a web service and receiving JSON back. The JSON object that I receive has multiple properties, although only one is shown in the code snippet below for simplicity. To map the JSON data to the object properties, I am using ko.mapping.fromJS function. However, the UI does not update with the fetched data. Manually updating the observable works fine, but not when using ko.mapping.fromJS.

Javascript

function AppViewModel() {
var self = this;
self.firstName = ko.observable("Bert");

$.ajax({
    dataType: 'json',
    async: true,
    type: 'POST',
    url: '/echo/json/',
    data: {
        json: '{"firstName":"Bob1"}'
    }
}).done(function(data) {
    console.log(data);

    //self.firstName(data.firstName);//This works
    self = ko.mapping.fromJS(data); //This doesn't

    console.log(self.firstName());
}).fail(function(jqxhr, textStatus, error) {
    alert('there was an error');
});
}

// Activates knockout.js
var avm = new AppViewModel();
ko.applyBindings(avm);

HTML

<p>First name: <strong data-bind="text: firstName"></strong></p>

You can run the jsfiddle where you will notice that the line below works correctly

self.firstName(data.firstName);//This works

However, the following line does not update the UI

self = ko.mapping.fromJS(data); //This doesn't

http://jsfiddle.net/texag93/fakdf5Lw/53/

Answer №1

Here are two essential things to remember: 1) It is crucial to create your initial view model using ko.mapping.fromJS, and 2) you must provide your existing view model as the second parameter to fromJS when updating it.

Therefore, your code should look something like this:

// Initialize knockout.js
var viewModel = ko.mapping.fromJS({firstName: 'Bert'});
ko.applyBindings(viewModel);

$.ajax({
    dataType: 'json',
    async: true,
    type: 'POST',
    url: '/echo/json/',
    data: {
        json: '{"firstName":"Bob1"}'
    }
}).done(function(data) {
    console.log(data);

    ko.mapping.fromJS(data, viewModel);

    console.log(viewModel.firstName());
}).fail(function(jqxhr, textStatus, error) {
    alert('An error occurred');
});

View the updated example here: http://jsfiddle.net/fakdf5Lw/56/

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

Tips for detecting web elements using Selenium within an iframe with Javascript

https://i.sstatic.net/9q3yq.pngWhen attempting to automate a wiki page using Selenium WebDriver, I am encountering difficulties identifying web elements within an iframe. dri.switchTo.frame(frameid); This is the iframe in question: <iframe frameborde ...

Most effective method for retrieving data from a database to display on a React user interface

I am currently working on a project where I need to show the value of a collection property stored using mongoose in my react app's client side whenever a user clicks a button. I am attempting to retrieve the value on click and then use setState to s ...

Acquire image dimensions with Javascript when uploading a file

I am working with a file upload interface where users will be uploading images. My goal is to validate the height and width of the image on the client side. Is there a way to determine the size of an image using just the file path in JavaScript? Important ...

Encountering a problem while integrating Vuetify into a Vite project

After setting up a Vite project, creating a navigation component, and implementing a router, I decided to integrate Vuetify into the project using npm i vuetify. However, I encountered the following error: Uncaught Error: [Vuetify] Could not find injected ...

What is the best approach for creating a test that can simulate and manage errors during JSON parsing in a Node.js

My approach to testing involves retrieving JSON data from a file and parsing it in my test.js file. The code snippet below demonstrates how I achieve this: var data; before(function(done) { data = JSON.parse(fs.readFileSync(process.cwd() + '/p ...

What is the procedure for transforming a JSON response into an array?

In my JSON response, I would like the values to be listed instead of appearing as a comma-separated single line. Here is a snippet of my code: URL url = new URL(urlStr); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMeth ...

Is it possible to change XML using Ajax technology?

Is it possible to update a value in an XML file using JavaScript/Ajax? I've managed to access the XML file with Ajax and utilize its values in my script. Now, I want to send any updates made by the script back to the XML file on the server using Ajax ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

Transmitting JSON securely to a server using an HTML form webpage

Currently, I have an HTML page with a form that communicates with a server using JSON requests. The purpose is to load user's previous answers upon loading and save new answers when the submit button is pressed. Each user has a unique user_id attribut ...

Tips for preserving data while attempting to access the schema

Attempting to store data from a book that includes author and genre information, referenced in separate files. The issue arises when making the reference in the main schema. Although the book carries details of the book itself, it fails to establish refer ...

Having trouble calling a method from React Native to Android native with a custom module

I am attempting to invoke a native method from react-native, but I am encountering an error. The issue is specific to the Samsung a70 device, as it works fine on some real devices and emulators. Below are the details of my code where I am trying to print f ...

ignore any anchors beyond the second index

I am working with a django-qcm that has dynamic sections triggered by anchors and utilizes the scroll snap type property. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv ...

What meaning does the symbol "===" carry in the context of JavaScript or jQuery?

Question on Equality: JavaScript === vs == : Does it matter which “equal” operator I use? The 3 different equals I'm puzzled by the following code snippet: data.toPage = $('div#someID'); if ( typeof data.toPage === "s ...

The functionality of JavaScript in jQuery mobile seems to require a manual refresh to work properly

Recently, I encountered an issue with my jQuery mobile page that contains JavaScript. The trouble is that the JavaScript doesn't function properly until the page is refreshed. Below is the snippet of code causing the problem: jQuery(function($) { ...

Make sure to retrieve the data before displaying the child components in React

Attempting to generate a list of selector options from external JSON data. Almost there, but part of the code is executing before the data loads, causing no children to be appended. There must be a way to solve this issue, just unsure how to do it in this ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

Creating JSON formatting for Google Charts using C#

Currently, I am attempting to generate JSON output from C# for the purpose of using it with a Google Chart. My current approach involves using JSON.Net: JArray arrB = new JArray( from c in cards where ...

What is the best way to extract the lowest and highest values from a `rangpicker` when using a price slider?

Can someone provide assistance on retrieving the minimum and maximum value after a mouse-drag operation? Kindly review the code snippet below: <div id="double_number_range" style="margin-top: 13px;"></div> <script type="text/javascrip ...

Trigger route handlers on both, successful authentication and failure, when using passport.js with a Node.js and Express.js REST API

Check out this simple login/token process using passport basic strategy for a Rest API: The Route: router.get('/token', authenticate.basic, controller.token); Authenticate Basic Strategy: authenticate.basic = passport.authenticate('basic ...

CakePHP ensured secure data by updating and escaping quotes

When working with the cakephp framework, I encountered a unique array structure like this: $myUniqueArray = array('x' => 10, 'y' => 20, 'z' => 30, 'w' => 40, 'v' => 50); After serializing i ...