I have an example working on which is working with static JS based JSON formatted data but when I parse same data through Ajax it does not work.
HTML CODE:
<table>
<thead>
<tr><th>File Name</th></tr>
</thead>
<tbody data-bind="foreach: attachments">
<tr><td data-bind="text: Filename" /></tr>
</tbody>
</table>
This is my JS code:
function testAjax(handleData) {
$.ajax({
url: 'form2.php',
type: "post",
data: '',
dataType: 'json',
success: function(data){
handleData(data);
},
error:function(data){
alert('Failed');
}
});
}
function localData(){
var data = [{"Filename":"f8.doc"},{"Filename":"f3.doc"}];
return data;
}
$(function () {
var ViewModel = function() {
var self = this;
self.getAttachments = function() {
testAjax(function(output){
var arr = [];
$.each(output, function (i) {
arr.push(new product(output[i]));
});
return arr;
});
/*var test = localData();
var arr = [];
$.each(test, function (i) {
arr.push(new product(test[i]));
});
return arr;*/
}
self.attachments = ko.observableArray(self.getAttachments());
self.refresh = function() {
self.attachments(self.getAttachments());
}
};
ko.applyBindings(new ViewModel());
});
var product = function (data) {
return {
Filename: ko.observable(data.Filename)
};
};
In this example code you can see a function named "localData" (It is commented). It contains JS based formatted JSON data set. But when I parse same data using ajax call using "testAjax" function. It has below code and results.
Code:
$data = array(
"0"=>array(
"Filename"=>"f8.doc"
),
"1"=>array(
"Filename"=>"f2.doc"
)
);
$encode = json_encode($data);
echo $encode;
Results from Ajax:
[{"Filename":"f8.doc"},{"Filename":"f2.doc"}]
Both "testAjax" & "localData show results alert(data.Filename) when I do in "product" before "return {Filename: ko.observable(data.Filename)};" But Ajax does not show data on page wile other local JS based formatted shows which is very strange to me.