Reading & Storing JSON data into knockoutja observableArray - json

I have following Json returned from an web api
{"PayHistories":
[{"Id":3,"RateChangeDate":"2014-09-03T06:00:00","Rate":10.00,"PayFrequency":7,"JobTitle":"Production Manager","Gendre":"M"}],
"JobCondidates":
[{"Id":3,"Resume":null,"JobTitle":"Production Manager","Gendre":"M"}],
"JobAssignments":
[{"Id":2,"DateStarted":"2014-09-03T05:00:00","DateFinished":"2014-09-03T05:00:00","DepartmentName":"Sales And Distributations","JobTitle":"Production Manager","SupervisorName":"Production Manager"}],
"Skills":
[{"Id":3,"SkillName":"Designer","DateSkillAcquired":"2014-09-03T06:00:00","SkillLevelCode":"103"},{"Id":4,"SkillName":"Agile Developer","DateSkillAcquired":"2014-09-03T06:00:00","SkillLevelCode":"104"}]
}
I want to save every Node into seperate knockoutjs observableArray()
here is
my code
self.skills=ko.observableArray();
self.PayHistories=ko.observableArray();
self.JobCondidates=ko.observableArray();
self.JobAssignments=ko.observableArray();
var employeeUri='/api/employees/';
function ajaxHelper(uri, method, data) {
//Clear error message.
self.error('');
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
})
.fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllEmployees() {
ajaxHelper(employeesUri, 'GET').done(function (data) {
// data is successfully loading into this data variable in this done function.
//But i want to store data seperatly into specific observableArray() say i want to store Skills int self.Skills observableArray()
});
}
I want to load data to proper observable for every node for Skills i want to store in self.Skills observable, for JobAssignements i want to store it into self.JobAssignments observableArray and voice versa. Thanks in Advance.

Have you tried Knockout's mapping plug-in. That would seem to do what you want automatically.

Related

Post JSON in DynamoDB via Lambda

I have trouble storing a JSON file in my DynamoDB table with the help of my Lambda function and my API Gateway on AWS. I have the following piece of code which gets executed once I press a button on my HTML site:
$('#submit').on('click', function(){
var example = {"number":"121212"};
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringify(example),
contentType: "application/json",
success: function(data){
location.reload();
}
});
return false;
});
When pressed the website reloads, hence I assume function has successfully executed. However my problem is that the data does not arrive in the correct format in the lambda function and hence does not execute properly. When checking in CloudWatch it is shown as { number: '121212' } instead of {"number":"121212"}. Any idea how I can make sure that the value 'arrives' has a valid JSON format in my Lambda function?
Here's my Lambda function:
exports.handler = function index(e, ctx, callback) {
var params = {
Item: { number: e.number },
TableName: 'collectionOfNumbers'
};
docCLient.put(params, function(err, data) {
if (err) {
callback(err, null);
} else {
callback(null, data);
}
});
}
If I'm reading this right, e.number is the value of the JSON parameter 'number' that you are passing in, e.g. '121212'. I'm making the assumption from the usage that docClient is putItem under the hood.
I think your Item param should look like:
Item: {"number": {N: e.number}}
See AWS Docs for info regarding PutItem https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html

Wrong data format for store loadData method ExtJS

I want to call JSON data as much as the amount of data in the store. Here is the code:
storeASF.each(function(stores) {
var trano = stores.data['arf_no'];
Ext.Ajax.request({
results: 0,
url: '/default/home/getdataforeditasf/data2/'+trano+'/id/'+id,
method:'POST',
success: function(result, request){
var returnData = Ext.util.JSON.decode(result.responseText);
arraydata.push(returnData);
Ext.getCmp('save-list').enable();
Ext.getCmp('cancel-list').enable();
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
id++;
});
storeARF.loadData(arraydata);
StoreASF contains data[arf_no] which will be used as a parameter in Ajax request url. StoreASF could contain more than one set of the object store, so looping is possible. For every called JSON data from request would be put to array data, and after the looping is complete, I save it to storeARF with the loadData method.
The problem is, my data format is wrong since loadData can only read JSON type data. I already try JSON stringify and parse, but couldn't replicate the data format. Any suggestion how to do this? Thank you.
Rather than using Ext.util.Json.decode(), normalize the data in success() method using your own logic. For example:
success: function (response) {
console.log(response);
var myData = [];
Ext.Array.forEach(response.data, function (item) {
myData.push({
name: item.name,
email: item.email,
phone: item.phone
});
});
store.load();
}

Trying to pass list of ids to the M-V-C Action through Ajax Function

I am trying to get and store the Ids of all the selected check-boxes in the JavaScript object. And then passing this object as a data to my JSON Action. I am able to successfully get the Ids of all the selected check-boxes, but when I am passing this object to my action I am getting null. Following is my code:
$("#btnSave").on('click', function () {
var selected = [];
$('input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '#Url.Action("SaveRecords", "Users")',
data: { ids: selected },
cache: false,
type: "GET",
success: function (data) {}
});
});
My Action:
public JsonResult SaveRecords(List<int> ids) //Here I'm getting Null.
{
return Json(true, JsonRequestBehavior.AllowGet);
}
As suggested in the comments, since you are saving data POST is more appropriate than GET. Also, I think you will save yourself some trouble by using JSON as input - you're already using it as output format from the action. This means your AJAX call will look like this:
$.ajax({
type: 'POST',
url: '#Url.Action("SaveRecords", "Users")',
contentType: 'application/json',
data: JSON.stringify(selected),
success: function (data) { /* ... */ }
});
When I say "save yourself trouble by using JSON as input" I mean that model binding collections and complex types in MVC can be a bit tricky when sending data as a form post - google it and you'll see that there are several implementation characteristics to be aware of. In my experience, using JSON for structured data posted with AJAX just works much more like what you would expect.

ASP MVC 3 complex multi parameters kno

in my previos question Asp MVC 3 json complex object not initialize properties
My mistake was in JSON convert from Knockout and after one more time with JSON.stringify(data).
Now evering working fine with one parameter,
but I wonder about if I need send to MVC controller two or more parameters one of them is knowckout data = ko.toJSON(viewModel); variable other one is some text.
var settings = ko.toJSON(viewModel);
var parameters = JSON.stringify({ id : *"guid"*, data : settings });
$.ajax({
url: '/KioskAjax/SaveSettings/',
type: "POST",
data: parameters,
dataType: "JSON",
contentType: "application/json; charset=UTF-8",
success: function (result) {
alert('ok');
}
});
[HttpPost]
public JsonResult SaveKiosksSettings(Guid id, GlobalData data)
{
return Json(false.ToString(), JsonRequestBehavior.AllowGet);
}
In this example id is getting value, but GlobalData parameters is null again,
i think this is because I use JSON.stringify again, but how build correct JSON for controller call if I have knowckout object ?
thanks.
ko.toJSON(myObject) does a ko.toJS(myObject) and then a JSON.stringify(myObject).
So, you could choose to use ko.toJS(myObject) to get a clean copy of your data and then JSON.stringify it with your other data, as you are already doing.

Send generic JSON data to MVC2 Controller

I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers. The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model. So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.
My ajax call:
function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
// Make a call to the server to process the object
var jsonifiedObject = JSON.stringify(object);
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: jsonifiedObject
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});
}
My MVC Controller:
public ActionResult SaveForm(string obj)
{
// Ok, try saving the object
string rc = PassJSONToSomething(obj.ToString());
string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
return new ContentResult { Content = message, ContentType = "application/json" };
}
The problem is that obj is always null. Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server? I'm using MVC2. This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.
Thanks very much.
Have you tried something like that?
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: {obj :jsonifiedObject}
, contentType: 'application/json; charset=utf-8'
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});