The Ajax response fails to update my viewmodel

I have a value and a list that I need to update from within an Ajax callback. After retrieving a fresh value using .get(), I try to assign it to my view model's property, but the UI does not refresh properly. Below is the code snippet:

function SearchViewModel() {
    this.count = ko.observable(count);
    this.list = ko.observableArray(list);

    this.addPage = function() {
       var form = $('#form');
       var serializedData = form.serialize();
       
       $.get("{% url 'search:search' %}", serializedData, function(response){
           console.log(this.count); // returns undefined
           
           this.count = response.count;
           
           console.log(this.count); // now has the correct value, e.g. 20, but UI does not update
       });
   };
}

In addition to updating the count, I also want to modify the list in the callback. However, currently even updating the simple count value is not reflected on the UI. Despite trying various solutions found on stackoverflow, none of them seem to work.

Answer №1

Give this a shot:

this.updateCount(response.count);

That should solve your issue.

If you want to learn more about observables, take a look at

There's also a potential scope problem in your code. When referencing 'this' in the callback, it may not always refer to the viewModel. To address this, add the following line outside of the callback:

var self = this;

Then within the callback, make sure to use 'self' instead of 'this':

self.updateCount(response.count);

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

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

After implementing ajax jQuery with Laravel 10, this page is experiencing technical difficulties

Seeking assistance from experienced individuals in dealing with Ajax jQuery within the context of Laravel. I have encountered a problem that has proven difficult for me to resolve on my own. Sample html code: <li> <a href="" onclick ...

What is the method for conducting an Ajax request?

Currently, I am deeply involved in a personal project to enhance my skills with Rails. The project involves developing a task management application that encompasses three primary states: todo, in progress, and done. After numerous days of trial and error, ...

What is the process for retrieving the address of the connected wallet using web3modal?

I've been working on an application using next.js and web3. In order to link the user's wallet to the front-end, I opted for web3modal with the following code: const Home: NextPage = () => { const [signer, setSigner] = useState<JsonRpcSig ...

Utilizing Bootstrap modal to insert data into phpMyAdmin database - a comprehensive guide

I'm attempting to insert data into my localhost database using a Bootstrap modal in conjunction with Laravel 5.2. Here is the PHP function I am using: public function addReport(Request $request) { $postreport = new PostReport(); $postreport- ...

Function exported as default in Typescript

My current version of TypeScript is 1.6.2 and we compile it to ECMA 5. I am a beginner in TypeScript, so please bear with me. These are the imported library typings. The contents of redux-thunk.d.ts: declare module "redux-thunk" { import { Middle ...

What is the best way to move between websites or pages without having to reload the current page using a selector?

Have you ever wondered how to create a webpage where users can navigate to other websites or pages without seeing their address, simply by selecting from a drop-down menu? Take a look at this example. Another similar example can be found here. When visit ...

Why is it impossible for me to delete the class / property of this object?

Within a series of nested divs, there are additional divs containing multiple imgs. The goal is to cycle through these images using CSS transitions. To achieve this, a JavaScript object was created to track the divs, sub-divs, and images. Three arrays were ...

Guide to uploading multiple images to an Amazon AWS S3 bucket using Node.js, Angular, and JavaScript

Can anyone share insights on where and how E-commerce websites typically upload their product images? Has anyone had experience using Amazon AWS S3 bucket for this purpose? Additionally, does anyone know how to upload or retrieve multiple images at once ...

Incorrect ASP.NET method called by jQuery ajax request

Here is an example of an ajax call: $.ajax({ type: "GET", url: "/api/action/deleteData?issueID=16", success: function (data) { console.log(data) }, ...

Looping through a dynamic array in Vue.js

I am working with two arrays: days:[0,1,2,3,4,5,6] and wdays:[2,3,6] My goal is to iterate through both arrays and display the output as follows: 0 : not present 1 : not present 2 : present 3 : present 4 : not present etc... The implementation should be ...

Is the CRSF protection compromised when a CRSF token is sent alongside an ajax request?

When submitting a form, I ensure security by checking for a CSRF token and validating it. Now, I want to maintain the same level of security when using ajax to submit the form. The ajax request does not actually submit the form itself; it simply sends da ...

Attempting to modify information in vue.js

I have been facing an issue with overriding data in the App.vue component. It seems that every time I try to update the data in my main.js file, the component still takes the default data. I am working with webpack as well. App.vue <template> & ...

transferring a specific dropdownlist value to a servlet using xhr

I am currently facing an issue where I need to pass the clicked value of a dropdown list to my servlet in order to execute a SQL query with the received value. My approach involves using Ajax as shown below: function showProject(prj) { xmlhttp = GetXm ...

toggle switch for numerical input

Whenever the "Qty" radio button is selected, I need to activate an input box that accepts numbers. Conversely, when the "rate" radio button is clicked, I want to disable this input box. This is how I designed it: <input type="radio" class="radioBtn" ...

Welcome to the awe-inspiring universe of Typescript, where the harmonious combination of

I have a question that may seem basic, but I need some guidance. So I have this element in my HTML template: <a href=# data-bind="click: $parent.test">«</a> And in my Typescript file, I have the following code: public test() { alert( ...

Adjust the width of the dropdown menu to match the text input field using jQuery

Struggling with jquery-mobile to collect user information, I am facing an issue aligning the width of my select menu with the text input fields. Despite successfully matching the background and border colors of the select menu with the text input fields, ...

How can you set a condition for when no matches are found in a list filter?

I recently came across a fascinating example on W3 Schools that taught me how to implement a search filter. Below, I have customized it for everyone's reference. I am interested in modifying it to only display a list item with the message: No matche ...

Instead of uploading multiple files at once, allow users to upload individual files by clicking on the table row

In my dynamic table, there are 4 columns. The first 3 columns in each row have an input type='file' where users can choose a file to upload, and the 4th column has a submit button aligned with the rows. While submitting files in the first row wor ...

Utilizing Codeigniter Ajax to return multiple rows in an ajax call, implementing two conditions (AND) in the SELECT query within the model file

When I click on the 'invoice number' in my 'purchase list', I want to open a collapsible table that will display the list of products matching the invoice number. To achieve this, I am utilizing jQuery to create the collapsible table an ...