Jack The Baker
Jack The Baker

Reputation: 1883

knockout push data from ajax to observableArray

I want to push data from ajax to knockout observableArray , but it give me an error:

The argument passed when initializing an observable array must be an array, or null, or undefined.

efine(['uiComponent', 'ko', 'jquery'], function (Component, ko, jquery) {

    return Component.extend({
        initialize: function () {
            this._super();

            /* State and cities */

            this.selectCity();
        },

        selectCity: function () {
var myViewModel = {}; 
            state = ko.observableArray([]);

            jquery.ajax({
                url: 'http://127.0.0.1/magento/hamechio/region.php',
                type: "GET",
                dataType: "json",
                success: function(data) {
                    myViewModel = data;
                    state.push(data);
                }
            });

            console.log(state); 
        }

    });
});

Upvotes: 0

Views: 740

Answers (3)

Negi Rox
Negi Rox

Reputation: 3912

this line should be change as per my knowledge.

 state = ko.observableArray([]);

to this

var state = ko.observableArray();

Upvotes: 2

meilide12
meilide12

Reputation: 21

This is a ajax scope ques.

you can use 'var'.

like this:

var state = ko.observableArray([]);

Upvotes: 2

Jonathan Twite
Jonathan Twite

Reputation: 952

Can I suggest looking through the Documentation that has lots of working examples: https://knockoutjs.com/documentation/observableArrays.html

Firstly, your View Model is the object on which all of your programme is built on. This object contains all of the data to show (as knockout observable property "methods") and commands to receive (functions). Therefore you need to define the view model to contain everything your application needs to do:

var viewModel = {
    //Bindings
    state = ko.observableArray();
}

Now you can write to the viewModel.state():

if data is an array and you don't want to track changes to data's items:

viewModel.state(data);

or push them one at a time:

data.foreach(function(el){ viewModel.state.push(el); });

If you want to track changes to each individual item's properties, you will need to use the second method and convert each element into an object composed of ko.observables.

Upvotes: 0

Related Questions