0

I have such code. The main problem is that var jsonOfLog = JSON.stringify(data); gives correct JSON "[{"name":"Jhon"},{"name":"Nick"},{"name":"Sanders"}]" but var jsonOfLog = JSON.stringify(test); gives undefined.

Why? It's problem with types or something else? How to fix this?

function AppViewModel() {

    self = this;
    self.items = ko.observableArray();
    self.addItems = function () {
        self.items.push({ Name: 'Test', Date: 'Test', Time: 'Test'});
    }
    function time_format(d) {
        hours = format_two_digits(d.getHours());
        minutes = format_two_digits(d.getMinutes());
        seconds = format_two_digits(d.getSeconds());
        return hours + ":" + minutes + ":" + seconds;
    }
    function format_two_digits(n) {
        return n < 10 ? '0' + n : n;
    }
    self.save = function () {
        data = [{ name: 'Jhon' }, { name: 'Nick' }, { name: 'Sanders' }];
        var test = self.items;
        var jsonOfLog = JSON.stringify(test);

        debugger;
        $.ajax({
            type: 'POST',
            dataType: 'text',
            url: "ConvertLogInfoToXml",
            data: "jsonOfLog=" + jsonOfLog,
            success: function (returnPayload) {
                console && console.log("request succeeded");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console && console.log("request failed");
            },

            processData: false,
            async: false
        });
    }
    self.capitalizeLastName = function () {
        debugger;

        var date = $("#date").val();


        $.ajax({
            cache: false,

            type: "GET",

            url: "GetByDate",

            data: { "date": date },

            success: function (data) {

                var result = "";

                $.each(data, function (id, item) {
                    var tempDate = new Date();
                    var tempTime = item.Time;
                    debugger;
                    tempDate =new Date(parseInt(item.Date.replace("/Date(", "").replace(")/", ""), 10));
                    self.items.push({ Name: item.Name, Date: (tempDate.getMonth() + 1) + '/' + tempDate .getDate() + '/' + tempDate.getFullYear(), Time: tempTime.Hours });
                });
            },

            error: function (response) {
                debugger;
                alert('eror');
            }
        });

    }
}

ko.applyBindings(new AppViewModel());
4
  • what does console.log(self.items) output? Commented Feb 22, 2016 at 17:59
  • Shouldn't your AppViewModel function have a return? Commented Feb 22, 2016 at 18:05
  • @Quantastical What does a constructor function need a return value for? Commented Feb 22, 2016 at 18:20
  • @Tomalak I was thinking they had just called AppViewModel() and passed the return into the ko.applyBindings parameter. Commented Feb 22, 2016 at 18:37

2 Answers 2

1

I see a couple things in your code that could be causing the problem.

First, the test variable is a reference to self.items, which is a Knockout observableArray and not a native JavaScript array. I'm not very familiar with Knockout, but that may not serialize as an array.

Also, on the first line of your constructor function, you are assigning to self without using var. This is assigning a value to a global variable instead of a local. If you have a similar construct elsewhere in your code, it is likely that the self reference is getting overwritten.

Sign up to request clarification or add additional context in comments.

3 Comments

"that may not serialize as an array" It doesn't. Knockout observables are functions, you get the array they contain when you call them (var test = self.items();). But that's by far not the only problem in the OP's code...
@Tomalak you are right! Thanks! Write answer i will accep it.
@A191919 Please be sure to fix the missing var issue as well.
0

You can't stringify an observable array like that; you end up stringifying the function and not the array. You should be using the ko.toJSON(viewModel) function for that.

Remember, in KnockOut, you always need to use the object.myObservableValue() to access the actual value of the observable (instead of object.myObservableValue), otherwise you end up using the function instead of the value.

1 Comment

I would not use ko.toJSON() here. Simply unwrapping the value and let jQuery do the JSON handling is the cleaner approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.