I'm learning TDD (in Javascript), and I wanted to know, what is the right way to use configuration variables? Should I make a separate class and have them be member variables of the class, and pass an instance of the class to every object that needs it, or make a list of global variables and just use those? What are the benefits / setbacks of each method?
For example, I have to get data from a URL as follows:
function getData (remoteDataDelegate) {
remoteDataDelegate.getData(userInfoURL)
}
where userInfoURL is a configuration variable that I set elsewhere to the URL for a page on my site.
This is an example of how I do it:
function NewConfiguration() {
var config = {};
config.carriersSelector = NewCarriersSelector();
config.paymentMethodsSelector = NewPaymentMethodsSelector();
return config;
}
Usage:
function NewOrderModel(request, searchRequest) {
var configuration = NewConfiguration();
// ... other variables code
var that = {
getContentSuccess: function(cb) {
// .. setup code
$.ajax({
type: 'GET',
url: request.page,
dataType: 'json',
data: request.data,
async: request.async,
success: function(data) {
if (data.status === 'success') {
cb(data.html, activeCustomer, step, configuration);
}
if (data.status == 'flash') {
flash(data.flash);
}
},
complete: request.complete
});
},
}
You will notice that the configuration is not being injected. for me, in this sample code the configuration never changes. Now my request objects change so they get injected, so I can mock those out or redirect the pages.
Global variables are usually set by the setUp method of your TestCase.
Related
I am calling a function on click of li data. Am passing the li data into that function and am trying to modify the data, but the data is not getting modified. Please suggest. Here is the plunkr.
https://next.plnkr.co/edit/ENExN1q40yY9dVFL?open=lib%2Fscript.js&deferRun=1&preview
$scope.selectRow = function(folders) {
console.log(folders);
folders = 'apple';
$http({
method: "GET",
url: "https://reqres.in/api/users?page=2",
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
folders = response.page;
});
}
To achieve that you need to change the $scope.folderList not the folders.
Changing the function to this:
$scope.selectRow = function(folders) {
$http({
method: "GET",
url: "https://reqres.in/api/users?page=2",
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
var index = $scope.folderList.indexOf(folders);
if (index >= 0 ) {
$scope.folderList[index] = String(response.data.page)
}
});
}
https://next.plnkr.co/edit/h3XKo5klP2F1qmAg?open=lib%2Fscript.js&deferRun=1
Folders is a variable that only exists in the method in your controller and then in the ng-repeat directive in your Html. Nowhere else does it exist so it's basically not a valid variable and is out of scope. In the ng-repeat directive you assign a name to the items in a list, so you could call it fuzzlebumps and it would still work.
So my suggestion: if you want to keep a variable in scope correctly do this in your controller to initialise it:
$scope.nameOfVariable;
Or in your case:
$scope.folders;
This is creating a variable that is bound to the scope. Scope is very important in JS so do a google search for the basics mate.
What CGI API can you use to replace $.getJSON() with $(ajax)...POST. GET is used for everything (ie: GET, PUT, POST, DELETE) when using CGIDEV2 in an IBM i environment? I dont want to pass my parameters the traditiontal way eg: $('[name="EMAIL"]').val() rather I want to pass JSON object string eg: {"form" : [{ "email": "yardpenalty#yahoo.com"}]}.
We are able to perform PostToGet callbacks using the $.getJSON() using CGIDEV2 but I can't use $.ajax in its fullest. Here is what we do now which is all GET requests
PHP/JS:
// load all parameters
data = 'INSTANCE=<?echo trim($PATH_INSTANCE)?>' +
'&FUNCTION=<?echo urlencode(trim($FUNCTIONCODE))?>' +
'&USER=' + $('[name="USER"]').val() +
'&CONTACT=' + w$('[name="CONTACT"]').val() +
'&EMAIL=' + $("input[name='EMAIL']").val() +
'&MSG=' + $('[name="MSG"]').val() +
'&TYPE=' + $('[name="TYPE"]').val();
// Call the RPG REST JSONP program
$.getJSON( "http://www.domain.com:8082/rest/RPGLEPGM?callback=?",data )
.done(function( json ) { ... }
//Domain is actually
http://www.domain.com:8081
RPGLE PGM:
Begsr $Incoming;
cgiPostToGet(); // Convert POST to GET
callback = cgiParseGet('callback'); // callback
p#Function = cgiParseGet('FUNCTION');
Endsr;
But I want to be able to use the other AJAX methods doing various actions such as simply updating records .post()/.ajax() on the fly or simple .get() ajax calls without creating a callback. I don't want to have to use getJSON every time I use ajax not to mention its bad practice to POST on a GET, but from what I understand the .getJSON() provides JSONP functionality while the others do not by default.
EDIT: We do have our ajax RPGLE PGMS on a different port than the actual website so JSONP is necessary and the client knows its JSONP because we pass the callback function back.
Since our ajax RPGLE PGM CALLS are on a different port than the PHP requests (think different domains on a host server) this qualifies as cross-domain requests; therefore, we must pass the &callback=? function/wrapper back to the client using JSONP (or Cors if security is an issue). I found a really good piece on JSONP here on SO and this is exactly what this ajax call is using.
RPGLE the jQuery ajax requests are made possible by using some sort of CGI API accessible on your OS/400 - IBM i Web environment. When calling (CALLB or CALLP) an RPGLE PGM using ajax we are actually making a procedural call, but when using global temps we are actually making a SQL Procedural CALL which is way more expensive in terms of resources which is why Web Services are becoming more popular.
It is more practical to not only pass javascript objects from the form data on request but to return JSON objects with Ajax requests than storing global temp data in the db2 environment and processing it into a PHP array on the response.
By processing the JSON string on the client instead of using both server memory and drive space and disk read/writes necessary for PHP arrays and global temp files we are really able to take advantage of more modern web design practices.
Here is a working example of using $.ajax/PHP/RPGLE correctly without using $.getJSON():
<script>
$(document).ready(function(){
GetEmail("#email", '<?php echo trim($USER)?>', '<?php echo $PATH_INSTANCE?>');
FormValidation();
});
function FormValidation(){
//Variables created without the keyword var, are always global, even if they are created inside a function.
var form = $('#<?echo $PAGEID?>');
var FormError = $('.alert-danger',form);
var success = $('.alert-success',form);
form.validate({
focusInvalid: false, // do not focus the last invalid input
onkeyup: false,
ignore: ".ignore", //required for hidden input validation ie: hiddenRecaptcha
rules:{
"TYPE": {
required: true,
},
"MSG": {
required: true,
rangelength:[40,1000]
},
"CONTACT": {
required: {
depends: "#newuser:checked"
}
},
"EMAIL": {
required: true,
email: {
depends: function() {
if(!$("#newuser:checked"))
return true;
else
return false;
}
},
HTH_TelephoneEmail: {
depends: function() {
if($("#newuser:checked"))
return true;
else
return false;
}
}
},
hiddenRecaptcha: {
required: function () {
if (grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},
messages: { // custom messages for form validation input
"TYPE": {
required: 'Please select an option as it pertains to your inquiry'
},
"MSG": {
required: 'Please provide some content as it pertains to your inquiry'
},
"CONTACT": {
required: "Please enter a contact person or company"
},
hiddenRecaptcha: {
required: function() {
$(".g-recaptcha:first").tooltip("enable").tooltip("show");
}
}
},
showErrors: function(errorMap, errorList) {
// Clean up any tooltips for valid elements
$.each(this.validElements(), function (index, element) {
element = $(element);
NoError_ToolTip(element);
});
// Create new tooltips for invalid elements
$.each(errorList, function (index, error) {
element = $(error.element);
message = error.message;
Error_ToolTip(element,message);
});
},
invalidHandler: function (event, validator) { //display error alert on form submit
success.hide();
$(document).scrollTop( $(".form-body").offset().top );
},
submitHandler: function () {
Submit_Complete();
}
});
function Submit_Complete(){
var obj = form.serializeObject();
console.log(obj);
$(".g-recaptcha:first").tooltip("disable").tooltip("hide");
$('.shell').html('<div class="loading"><span class="caption">Sending...</span><img src="/images/loading.gif" alt="loading"></div>');
$.ajax({
type: "POST",
url: "http://www.domain.com:8082/rest/RPGPGM2?callback=?",
data: obj,
//contentType: "application/json; charset=utf-8",
dataType: "jsonp"}).
done(function(data){
$(".shell").html('<label class="msg xs-small">' + data["MESSAGE"] + '</label><br><br><br><br><br><br><br><br><br>'+
'<div class="caption right">'+
'Home <i class="fa fa-home"></i>'+
'</div>');
}).
fail(function(){
$(".shell").html("<label class='msg xs-small'>We're Sorry!<br><br><br><br><span class='text-danger'>Unfortunately this inquiry cannot be processed at this time." +
"<br>Please try again at a later time or give us a call at:</span><br><br>+1.800.406.1291</label><br><br><br><br><br><br><br><br><br>"+
'<div class="caption right">'+
'Home <i class="fa fa-home"></i>'+
'</div>');
});
}
}
/**
* Serializes form data/objects. This actually creates a javascript object which our CGIAPI is capable of handling!
*
*/
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
var $value = '';
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>
We can make RESTful calls by using some type of CGI API such as QtmhRdStin or by creating Web Services. This solution is of the former.
Here is a list of the basic CGI APIs:
RPGLE PGM:
// $Incoming: Test and load the incoming parameters
Begsr $Incoming;
cgiPostToGet(); // Convert POST to GET
callback = cgiParseGet('callback'); // never delete - unique key for the request
p#UserID = cgiParseGet('USER');
if (%scan(#lf:p#UserID) <> 0);
p#UserID = *blanks;
endif;
p#Instance = cgiParseGet('INSTANCE');
if (%scan(#lf:p#Instance) <> 0);
p#Instance = *blanks;
endif;
p#Function = cgiParseGet('FUNCTION');
p#Contact = cgiParseGet('CONTACT');
if (%scan(#lf:p#Contact) <> 0);
p#Contact = *blanks;
endif;
p#Email = cgiParseGet('EMAIL');
p#Msg = cgiParseGet('MSG');
p#Related = cgiParseGet('TYPE');
exsr $InzSr;
Endsr;
Begsr $Outgoing;
// Tell Consumer that a JSON string will be sent
ajx_data = 'Content-type: text/javascript' + CRLF + CRLF; // DO NOT CHANGE THIS LINE!!!
QtmhWrStout(ajx_data: %len(%trimr(ajx_data)): ajx_err);// DO NOT CHANGE THIS LINE!!!
ajx_data = %trim(callback) + '(' + %char(LBrace); // DO NOT CHANGE THIS LINE!!!
QtmhWrStout(ajx_data: %len(%trimr(ajx_data)): ajx_err);// DO NOT CHANGE THIS LINE!!!
ajx_data = '"MESSAGE":"' + %trim(p#message) + '"';
QtmhWrStout(ajx_data: %len(%trimr(ajx_data)): ajx_err);
// load the final right brace to complete the JSON string
ajx_data = %char(RBrace) + ');'; // DO NOT CHANGE THIS LINE!!!
QtmhWrStout(ajx_data: %len(%trimr(ajx_data)): ajx_err); // DO NOT CHANGE THIS LINE!!!
Endsr;
****NOTE****
If we can't serialize our form directly we must build a javascript object like this:
var obj = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
$.ajax({
type: "POST",
url: "http://webservices.hthackney.com/web054S?callback=?",
data: data,
dataType:'jsonp'
}).done({ //do something on success });
Unfortunately you can POST using JSONP but you cannot read the header response.
I FINALLY found the solution to executing both db2 and ajax requests on a single DOMAIN.
SOLUTION HERE
If you need to perform AJAX requests on the SAME DOMAIN in an IBMi environment w/apache/PASE you need the following ScriptAlias and two directives in your http.conf file:
ScriptAliasMatch /rest/([0-9a-zA-Z]+$) /qsys.lib/rest.lib/$1.pgm
<Directory /qsys.lib/obj.lib/>
order allow,deny
allow from all
Header Always Set Access-Control-Allow-Origin *
Options +ExecCGI +Includes -Indexes +MultiViews
CGIConvMode %%MIXED/MIXED%%
</Directory>
<Directory /qsys.lib/rest.lib>
CGIConvMode %%EBCDIC/EBCDIC%%
Order Allow,Deny
Allow From all
Header Always Set Access-Control-Allow-Origin *
Options +ExecCGI -FollowSymLinks -SymLinksIfOwnerMatch +Includes -IncludesNoExec -Indexes -MultiViews
</Directory>
rest.lib member is where all of the ajax rpgle pgms reside.
obj.lib is where all CALL WEBXXX for db2 calls in PHP are located.
Now you are able to call AJAX requests under the /rest/$1PGM pattern.
For instance:
$.ajax({
type: "POST",
url: "http://www.domain.com/rest/WEB055S",
data: obj,
contentType: "application/json; charset=utf-8"
).
done(function(data){
$("#signupForm .loading").addClass("hidden");
//Successful Submit!
if(typeof data.MESSAGE != "undefined"){
clicked = 0;
$("#ok_msg").html(data.MESSAGE).show();
}
else{//ERROR
//console.log(data.ERROR);
$("#attendee #hth_err_msg").html(data.ERROR).show();
$('.add-attendee').addClass('hidden');
$('.edit-attendee').addClass('hidden');
}
}).
fail(function(){
$("#hth_err_msg").html("We're sorry, you're request cannot be processed at this time. It is likely the corporate system is under maintenance.").show();
});
I have a scenario to pass parameters from pentaho cde using kettle to pentaho data integration and then update the table using the passed parameter in PDI. How can i pass the parameter and get the passed parameter in PDI?
Thanks in advance!!!
You will need to use the Pentaho plugin builder, SPARKL.
With it you can upload a transformation as a callable endpoint and use a CDE dashboard to call it.
First of all, you need a transformation that expects parameters. You can try it with a test one before going to a more advanced transformation:
Example:
defining a parameter and fetching with a Get Variables step
Second you will create a new plugin on SPARKL.
Sparkl welcome screen
Give your plugin a name and add a kettle endpoint to it. If you now look at your pentaho-solutions/system folder, you will have a new folder with the plugin name. Open it and find the ktr file inside the subfolders to replace it with your transformation.
The last step is to add a new dashboard to your plugin and edit it. If you go to the datasources tab now, notice the datasources with 'endpoint' in the name. We will access them by code, but is good to know they are here so you can read data from it too, not just input data.
add a new resource of javascript to your CDE layout with the following code:
var myPluginName = {};
(function(myself) {
myself.runEndpoint = function (pluginId, endpoint, opts) {
if (!pluginId && !endpoint) {
Dashboards.log('PluginId or endpointName not defined.');
return false
}
var _opts = {
success: function () {
Dashboards.log(pluginId + ': ' + endpoint + ' ran successfully.')
},
error: function (){
Dashboards.log(pluginId + ': error running ' + endpoint + '.')
},
params: {},
systemParams: {},
type: 'POST',
dataType: 'json'
}
var opts = $.extend( {}, _opts, opts);
var url = Dashboards.getWebAppPath() + '/plugin/' + pluginId + '/api/' + endpoint;
function successHandler (json) {
if (json && json.result == false) {
opts.error.apply(this, arguments);
} else {
opts.success.apply( this, arguments );
}
}
function errorHandler () {
opts.error.apply(this, arguments);
}
if (endpoint != 'renderer/refresh' ) {
var ajaxOpts = {
url: url,
async: true,
type: opts.type,
dataType: opts.dataType,
success: successHandler,
error: errorHandler,
data: {}
}
} else {
var ajaxOpts = {
url: url,
async: true,
type: 'GET',
dataType: opts.dataType,
success: successHandler,
error: errorHandler,
data: {}
}
}
_.each( opts.params , function ( value , key) {
ajaxOpts.data['param' + key] = value;
});
_.each(opts.systemParams , function (value , key) {
ajaxOpts.data[key] = value;
});
$.ajax(ajaxOpts)
}
})(myPluginName);
You can change myPluginName with whatever you want but that enables you to call that endpoint sending parameters with any button. To do so you can use that code:
myPluginName.runEndpoint(
'myPluginName', // Plugin identifier.
'endpointName', // Put your endpoint name here!
{
params: {
'EXAMPLE_PARAMETER' : foo_bar
},
success: function() { Dashboards.fireChange('refresh', 1); alert('data sent'); },
error: function() { alert('Ops, something went wrong. Check the logs.'); }
})
You can keep track of the execution by monitoring the bi-server logs.
More information on the sources:
Diethard Steiner - Blog
Francesco Corti - Blog
Follow these guys, they are amazing.
You could do that, or you could just create a CDA data source, which takes a parameter as defined in your transformation.
Params are passed to CDA via the usual ¶mYOURPARAMNAME=x syntax on the URL.
In the transformation you get the parameter using the get variables step.
Did I miss something?
I am using worlight JSONstore. I am new to it. I tried searching that read all docs but didn't get much idea.
I have one login page from that I get some json data I want to store that data using jsonstore. and get that afterwards.
I made jsonstore adapter.
Json-Store-Impl.js
function getJsonStores(custData) {
var data = custData;
return data;
//custdata is json
}
function addJsonStore(param1) {
var input = {
method : 'put',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function updateJsonStore(param1) {
var input = {
method : 'post',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function deleteJsonStore(param1) {
var input = {
method : 'delete',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
after that I Create a local JSON store.
famlCollection.js
;(function () {
WL.JSONStore.init({
faml : {
searchFields: {"response.mci.txnid":"string","response.mci.scrnseqnbr":"string","response.loginUser":"string","request.fldWebServerId":"string","response.fldRsaImageHeight":"string","request.fldRequestId":"string","request.fldTxnId":"string","response.fldDeviceTokenFSO":"string","response.fldRsaCollectionRequired":"string","response.datlastsuccesslogin":"string","response.fldRsaUserPhrase":"string","response.fldRsaAuthTxnId":"string","response.rc.returncode":"string","response.datcurrentlogin":"string","response.mci.deviceid":"string","response.customername":"string","request.fldDeviceId":"string","response.fldRsaUserStatus":"string","request.fldScrnSeqNbr":"string","response.fldRsaImageWidth":"string","request.fldLangId":"string","response.fldTptCustomer":"string","response.encflag":"string","response.rc.errorcode":"string","response.fldRsaImagePath":"string","response.mci.appid":"string","response.mci.requestid":"string","response.rc.errormessage":"string","response.mci.appserverid":"string","response.fldRsaCollectionType":"string","request.fldAppId":"string","response.fldRsaImageId":"string","request.fldLoginUserId":"string","response.mci.sessionid":"string","response.mci.langid":"string","response.mci.remoteaddress":"string","request.fldAppServerId":"string","response.mci.webserverid":"string","response.fldRsaImageText":"string","response.fldRsaEnrollRequired":"string","response.fldRsaActivityFlag":"string"},
adapter : {
name: 'JsonStore',
replace: 'updateJsonStore',
remove: 'deleteJsonStore',
add: 'addJsonStore',
load: {
procedure: 'getJsonStores',
params: [],
key: 'faml'
},
accept: function (data) {
return (data.status === 200);
}
}
}
}, {
password : 'PleaseChangeThisPassword'
})
.then(function () {
WL.Logger.debug(['Take a look at the JSONStore documentation and getting started module for more details and code samples.',
'At this point there is no data inside your collection ("faml"), but JSONStore is ready to be used.',
'You can use WL.JSONStore.get("faml").load() to load data from the adapter.',
'These are some common JSONStore methods: load, add, replace, remove, count, push, find, findById, findAll.',
'Most operations are asynchronous, wait until the last operation finished before calling the next one.',
'JSONStore is currently supported for production only in Android and iOS environments.',
'Search Fields are not dynamic, call WL.JSONStore.destroy() and then initialize the collection with the new fields.'].join('\n'));
})
.fail(function (errObj) {
WL.Logger.ctx({pretty: true}).debug(errObj);
});
}());
When I clicked on login button I call getJsonStores like this -
getJsonStores = function(){
custData = responseData();
var invocationData = {
adapter : "JsonStore",
procedure : "getJsonStores",
parameters : [custData],
compressResponse : true
};
//WL.Logger.debug('invoke msg '+invocationData, '');
WL.Client.invokeProcedure(invocationData, {
onSuccess : sucess,
onFailure : AdapterFail,
timeout: timeout
});
};
I followed these steps
Is this right way? and how can I check jsonstore working locally or not? and how can I store my jsondata in JSONStore? Where should I initialize the wlCommonInit function in project?
plz Help me out.
Open main.js and find the wlCommonInit function, add the JSONStore init code.
WL.JSONStore.init(...)
You already have an adapter that returns the data you want to add to JSONStore, call it any time after init has finished.
WL.Client.invokeProcedure(...)
Inside the onSuccess callback, a function that gets executed when you successfully get data from the adapter, start using the JSONStore API. One high level way to write the code would be, if the collection is empty (the count API returns 0), then add all documents to the collection.
WL.JSONStore.get(collectionName).count()
.then(function (countResult) {
if(countResult === 0) {
//collection is empty, add data
WL.JSONStore.get(collectionName).add([{name: 'carlos'}, {name: 'mike'}])
.then(function () {
//data stored succesfully
});
}
});
Instead of adding [{name: 'carlos'}, {name: 'mike'}] you probably want to add the data returned from the adapter.
Later in your application, you can use the find API to get data back:
WL.JSONStore.get(collectionName).findAll()
.then(function (findResults) {
//...
});
There is also a find API that takes queries (e.g. {name: 'carlos'}), look at the getting started module here and the documentation here.
It's worth mentioning that the JSONStore API is asynchronous, you must wait for the callbacks in order to perform the next operation.
I am using KnockoutJS for data binding.
Following code is controller's action method
public JsonResult GetPeople()
{
var people = new List<Person>
{
new Person {Name = "aaaa", Address = "aaaaaaaaa"},
new Person {Name = "bbbb", Address = "bbbbbbbbb"},
new Person {Name = "cccc", Address = "ccccccccc"}
};
return Json(people, JsonRequestBehavior.AllowGet);
}
And bellow is the snippet of client side code
<ul data-bind="foreach: people">
<li>NAME:<span data-bind="text: Name"></span></li>
<li>ADDRESS:<span data-bind="text: Address"></span></li>
</ul>
<script>
function getPeopleFromServer() {
var people= [];
$.ajax({
url: "GetPeople",
cache: false,
type: "GET",
success: function (result) {
console.log("result= " + result);
people = $.parseJSON(result);
console.log("people= " + people);
}
});
return people;
}
function ViewModel() {
var self = this;
// data
self.people = ko.observableArray(getPeopleFromServer());
}
ko.applyBindings(new ViewModel());
</script>
The problem is that people variable in the getPeopleFromServer method is always null while result has proper value from the server.
Am I missing something?
Your $.ajax function is taking longer to complete than it's containing function, and so the containing function never popuplates people by the end of execution
One thing you can do is to add the following to your $.ajax:
$.ajax({
async: false,
url: "GetPeople",
.....
});
async: false will make the containing function 'wait' until ajax is finished. Your people var should be populated by the end of function execution. While this is a quick win, I agree with Tom that you should re-think how your ViewModel is handled.
#tom's comment is correct.
'success' is an inline async function. Basically, 'return people' happens before the 'success' function is called, because the ajax call is non-blocking. You need to redesign your ViewModel to work asynchronously (or turn off async), hopefully others will chime in with code fixes
Here's the fully commented fiddle he prophesied.
http://jsfiddle.net/bczengel/8Wqum/
people should be referred to either in the same view model. Or as self.people. I suggest you put the call to ajax inside the view model and then it will be clear.
So getPeopleFromServer() should be inside the viewmodel.
Out of interest you can also add
timeout: 600000 so that the call doesnt timeout.
Try to use ko.mapping plugin.
function ViewModelWrapper(jsonResult)
{
var self = this;
self.model = ko.mapping.fromJS(jsonResult);
}
http://knockoutjs.com/documentation/plugins-mapping.html