Frank B
Frank B

Reputation: 658

Can't get returned Array inserted into knockoutjs observableArray

I have the following view model. Upon logging in I want the user to have a select box listing all the cities in the database. Here's the view model

function ppfoViewModel(){
        var self= this;
        self.userName = ko.observable();
        self.password = ko.observable();
        self.loggedIn = ko.observable(false);
        self.validateUser = function(){
            if(self.userName()=='Admin'&&self.password()=='Admin'){ 
                var temp;
                self.loggedIn(true);
                $.get("dbhandler.php", { "fun": "cities"}, function (data) {self.cities(data);});               
            }else{
                self.loggedIn(false);
            }};
        self.cities = ko.observableArray()
        self.selectedCity = ko.observable();
        self.store = ko.observable();
        self.drink = ko.observable();
        self.test = ko.observable();
    };

The ajax request calls a page that returns the following string:

[{"cityName":"Provo","cityID":"1"},{"cityName":"Salt LakeCity","cityID":"2"}]

Here is the view.

<select data-bind="options: cities, optionsText:'cityName', selectedOptions: selectedCity""></select>

When I login I know I'm getting that string correctly however the select box has several blank spaces as it's options. I'm sure I'm missing something obvious here, but how can I get the array created by the php page and AJAX request into the observable array so it works? Thanks in advance for tolerating my ridiculousness.

Upvotes: 1

Views: 171

Answers (1)

thomaux
thomaux

Reputation: 19738

You need to parse the result back to a JSON object, like:

$.get("dbhandler.php", { "fun": "cities"}, function (data) {
    self.cities(JSON.parse(data));
});

Upvotes: 1

Related Questions