Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6374213
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T01:27:35+00:00 2026-05-25T01:27:35+00:00

Problem: I am trying to use knockout.js with jquery templates. The problem is that

  • 0

Problem:

I am trying to use knockout.js with jquery templates. The problem is that an $.ajax call returns values correctly, but when I try to insert them into the corresponding ko.observableArray, I get the correct number of rows, but the values are all undefined

The problem, according to my debugging is located in a for in loop in the success callback for an $.ajax call.

It seems that if I write:

for (item in myArray)
{
    alert(item.myProperty); // shows undefined
}

What am I doing wrong??!

Detailed setup follows.

Setup:

My template is:

<fieldset style="padding-top:10px;">
    <legend>Associated Cost Centres</legend>
    <table>
        <thead>
            <tr>
                <th>
                    Cost Centre
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody data-bind="template: {name:'actividadesAsociadas', foreach: viewModel.costCentres}"></tbody>
    </table>
</fieldset>
<script type="text/x-jquery-tmpl" id="actividadesAsociadas">
    <tr>
        <td data-bind="text: NameCC"></td>
        <td data-bind="text: CostCentreId"></td>
        <td><a href="#" data-bind="click: remove">Delete</a></td>
    </tr>
</script>

My javascript is:

function costCentre(CostCentreId, IdTransactionType, NameCC, ownerViewModel) {

    this.CostCentreId      = ko.observable(CostCentreId); 
    this.IdTransactionType = ko.observable(IdTransactionType); 
    this.NameCC            = ko.observable(NameCC);
    this.remove            = function() { ownerViewModel.costCentres.destroy(this) }
} 



function costCentreViewModel() { 

   // other methods

   this.costCentres = ko.observableArray([]);

    var self = this;self = this;
    $.ajax({url: "/[...route...]/GetCostCentres/" + @id,
        dataType: 'json',
        data: {},
        type: 'POST',
        success: function (jsonResult) {
            var mappedCostCentres = $.map(jsonResult, function(item) {
            return new costCentre(item.CostCentreId, item.IdTransactionType, item.Name, self)
             });
             for (cc in mappedCostCentres)
             {
                 self.costCentres.push(new costCentre(cc.CostCentreId, cc.IdTransactionType, cc.NameCC, self));
             }
       },
       error: function (result) {
             $('#ErrorDisplay').show().html('<p>' + result.responseText + '</p>');
       }
    });
    // test data
    this.costCentres.push(new costCentre(55, 54, "test", this));

    // other methods
}; 

var viewModel = new costCentreViewModel();
jQuery(document).ready(function () { ko.applyBindings(viewModel); });

The bit where the problem happens in the javascript code is:

for (cc in mappedCostCentres)
{
    self.costCentres.push(new costCentre(cc.CostCentreId, cc.IdTransactionType, cc.NameCC, self));
}

The reason being that cc.CostCentreId, cc.IdTransactionType and cc.NameCC all evaluate to undefined.

I know that this is the case, because the test data is displayed correctly by the jquery.tmpl template, whereas the rows that have been brought in by the $.ajax call just display as empty tags.

jsonResult:

The jsonResult returned by the $.ajax call looks like this (this is correct):

    [{"CostCentreId":5,"IdTransactionType":2,"Name":"Impuestos"},
{"CostCentreId":14,"IdTransactionType":3,"Name":"Transferencias Internas"}]

Questions:

  1. Having set up my for in loop (for(cc in mappedCostCentres)), why does:

cc.NameCC

evaluate to undefined, despite being able to see in firebug that the items in mappedCostCentres have the values that I expect?

  1. What better, or rather, working way is there to fill one array from another array?

Edit:

I am now trying the following code:

in my ViewModel (costCentreViewModel), I define:

this.GetCostCentres = function() {
    $.ajax({url: "/Admin/Accounts/GetCostCentres/" + @id,
            dataType: 'json',
            data: {},
            type: 'POST',
            success: function (jsonResult) {
                var mapped = $.map(jsonResult, function(item) {
                    return new costCentre(item.CostCentreId, item.IdTransactionType, item.Name, self)
                });
                self.costCentres = ko.observableArray(mapped);
                alert(self.costCentres.length);
            },
            error: function (result) {
                $('#ErrorDisplay').show().html('<p>' + result.responseText + '</p>');
        }
    });
};

Then I call (from outside the viewmodel definition):

var viewModel = new costCentreViewModel();
viewModel.GetCostCentres();
jQuery(document).ready(function () { ko.applyBindings(viewModel); });

It still doesn’t work. The problem in my mind is:

Why doesn’t this line work (everything else does):

self.costCentres = ko.observableArray(mapped);

I can only think it is the way I have defined my viewmodel object, using the constructor pattern, ie:

function myViewModel() {
this.costCentres= ko.observableArray([]);

...

this.GetCostCentres = function() {
   $.ajax(....);

}

but I honestly haven’t a clue. JavaScript is defeating me right now. Maybe I should go back to Quantum Cosmology?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T01:27:36+00:00Added an answer on May 25, 2026 at 1:27 am

    Looks like the main issue was that when trying to set the value of the observableArray on the result of an AJAX request, you were setting it equal to a new observableArray rather than setting the value of the existing one that was already bound to your UI.

    So, self.CostCentres = ko.observableArray(mapped)` will create a new observableArray that your UI is not currently bound against.

    self.CostCentres(mapped) would be the appropriate way to set an existing observableArray equal to an entirely new array.

    In a previous attempt, it did look like you were constructing a CostCentre twice to push it onto your observableArray. It is only necessary to create each CostCentre once.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am running into a problem trying to use AJAX and jQuery with ASP.NET
I am having a problem trying to use the prependTo() function in jQuery... for
Ok I have this problem I'm trying to use Jquery to load a partial
Trying to use JSTL but have the following problem: Index.xhtml page: <?xml version=1.0 encoding=UTF-8?>
I'm trying to use jGrowl in an aspx page. But I encountered a problem
I am trying to setup generic Knockout templates that can be toggled between edit
I am trying use Thread but i have some problem (I am beginner at
I'm experiencing a strange problem while trying to use the Ajax.BeginForm method of ASP.NET
I have a little problem I am trying to use MartkItUp JQuery rich text
I am trying use the jQuery table sorter plugin for a table that is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.