javascript array serializing - javascript

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());

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.

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.

Related

How to disable click in past days fullcalendar

I try to disable clickable past days.
I'm using dateClick but can't pass multiple args and have error:
*Uncaught TypeError: date.format is not a function
My function:
EDIT:
Dateclick function with ajax.
Now don't know how to disable click, when past days
dateClick: function (info, jsEvent, view, date) {
let currDate = info.dateStr;
// if (moment().format('YYYY-MM-DD') === currDate || date.isAfter(moment())) {
// return false;
// } else {
//
// alert('Date: ' + currDate);
// alert('ID: ' + $('#reservation-form #select-service').val());
// }
let selectServiceVal = $('select#select-service').val();
if (!selectServiceVal) {
alert('Najpierw wybierz usługę');
} else {
dateValue.val(currDate);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: getFreeHorus + selectServiceVal + '/' + currDate,
dataType: 'json',
method: "POST",
data: {
"id": selectServiceVal,
"date": currDate
},
beforeSend: function () {
$(".calendary-loader").css('display', 'block');
},
success: function (data) {
$(".calendary-loader").css('display', 'none');
if (data.message) {
alert('Wybierz poprawną datę')
}
displayHours(data.availableHours);
},
error: function () {
$(".calendary-loader").css('display', 'none');
alert('Błąd serwera, spróbuj później')
}
});
}
}
You can use select. This is how I did mine:
select: this.handleDateClick.bind(this),
//the handleDateClick funtion
handleDateClick(arg: any) {
let todaysDate = new Date();
let formattedDate = moment(todaysDate).format("YYYY-MM-DDTHH:mm:ss"); //formatted version of todays date so a comparison can be made
let s1 = arg.startStr;
let s2 = arg.endStr;
let currentdate = moment().isUTC();
let newDateObj = moment(s1).add(15, "m").format("YYYY-MM-DDTHH:mm:ss");
if (s1 < formattedDate) {
//This checks if time is in the past. If so,
alert("This date is in the past")

System.Data.Entity.DynamicProxies

I tried this code in my controller Can any one show me the solution:
public JsonResult GetMembers(Member member)
{
//var list = repository.GetAll().Select(x => new ViewModel.MemberView
//{
// Memberid = x.id,
// Name = x.name,
// EmailAddress = x.Email,
// Role = x.role.rolename,
// ReportingRoleId = Convert.ToInt32(x.reportingroleid)
//});
var list = repository.GetAll();
return Json(list , JsonRequestBehavior.AllowGet);
}
javascript function
<script type="text/javascript">
debugger;
alert('first');
google.load("visualization", "1", {packages:["orgchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Organization/GetMembers",
data :'{member:"+JSON.stringify(member)+"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Member Name"+data);
//var data = new google.visualization.DataTable();
//data.addColumn('string','name');
//data.addColumn('string', 'role');
//data.addColumn('string', 'ToolTip');
//for (var i = 0; i < r.length; i++) {
// var memberId = r[i][0];
// var Name = r[i][1];
// var role= r[i][2];
// var reportingrole= r[i][3] != null ? r[i][3].toString() : '';
// data.addRows([[{
// v: employeeId,
// f: Name + '<div>(<span>' + role + '</span>)</div><img src = "/Pictures/' + memberId + '.jpg" />'
// }, reportingrole, role]]);
//}
// var chart = new google.visualization.OrgChart($("#chart")[0]);
// chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r);
},
error: function (r) {
alert(r);
}
});
}
It was Error
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.NewProjects_A3B55EADDAEF6C59245BBD2495E29ECFE10B583596DB24AADF23A4990342D104'.
I had the same error, but this is worked for me, this is when you want to select
public MyDbContext() : base("name=MyDbContext"){this.Configuration.ProxyCreationEnabled = false;}
before you call yout table use this this.Configuration.ProxyCreationEnabled = false;
You should convert your data to list before returning it. EF return proxies for lazy loading and stuff. Try below code.
var list = repository.GetAll().ToList();
Also Look at this.
Why is EF returning a proxy class instead of the actual entity?

Date value being reduced by 1 when the client and the server are in different time zones

I'm using the code below to get a date value from a jQuery datepicker.
function GetViewModelData() {
var actionViewModel = [];
var rowCount = $('#myDynamicTable tbody tr').length;
var actionDate;
for (i = 1; i <= rowCount; i++) {
actionDate = document.getElementsByClassName("txtDateOfAction")[i - 1].value;
var parts = actionDate.split("/");
var dt = new Date(parseInt(parts[2], 10), parseInt(parts[1], 10) - 1, parseInt(parts[0], 10));
var rdtViewModel = new DetailsViewModel(0, dt);
actionViewModel.push(rdtViewModel);
}
var obj = new ReportViewModel(0, actionViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I'm then using the code below to send my value to an SQL server database.
var SubmitData = function() {
$(".btnSave").click(function() {
Loader();
var viewmodel = GetViewModelData();
var actionCode = $.trim($("#actionCode").val()).toLowerCase();
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Submission/Save',
success: function(data) {
$("#divMaster").html(data);
return false;
},
error: function(e) {
alert("An error occured");
return false;
}
});
});
}
The problem i'm facing is that if the client and the server are in different time zones, the date value the client selected is reduced by 1 when being saved on the server.
For example, if the client selects 19/01/2017, it is saved as 18/01/2017 on the server (in the database).
If the client is in the same time zone as the server, every things works fine.
How can resolve this issue?

Push 2 arrays after json loop

I need to run function "testfun 2 times", for each function I will have a few of names lets say testfun(5, global_user) // output [1,2,4,4,5] and for testfun(7, global_user) // output [9,10,11]
How I can put this 2 arrays in one array after I will run 2 functions?
testfun(5, global_user);
testfun(7, global_user);
function testfun(groupId, myUser) {
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url: itemsUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: loadTeamNames,
error: errorHandler
}
);
}
var arr = [];
function loadTeamNames(data){
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function(){
var name = $(this)[0].Name;
});
}
Thanks
With JS
var mergedArray = outputOne.concat(outputTwo);
With JQuery
var mergedArray = $.merge( $.merge( [], outputOne), outputTwo);
Since testFun() uses asynchronous methods you can't do anything immediately after running it twice without waiting for both instnces to complete. This is accomplished using promises
You could use $when() and return a promise from testFun(). Will need to move loadTeamNames into testFun to do it
$.when() won't complete until both of the promises are resolved
function testfun(groupId, myUser) {
var defer = $.Deferred();
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url : itemsUrl,
method : "GET",
headers : {"Accept" : "application/json; odata=verbose"},
success : loadTeamNames,
error : errorHandler
}
);
function loadTeamNames(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function () {
var name = $(this)[0].Name;
});
// resolve deferred and pass data to be used in `$.when()`
defer.resolve(results);
}
return defer.promise;
}
To use
$.when(testfun(5, global_user),testfun(7, global_user)).done(function (results1, results2) {
//do what you need to with arrays results1 & results2
});
Add defer.reject() in the errorHandler
Assuming that jsonObject.d.results is an array already, you can just do:
arr.concat(results)
This will concatenate your array so far with the new result. Have that code inside of loadTeamNames and each run of testfun will concatenate the result to your current array. not really sure what you're using all those variables inside of loadTeamNames for however.
function getTeamNames(groupId, myUser) {
var defer = $.Deferred();
var selectStr = "$select=Title,LoginName";
var orderbyStr = "$orderby=Title";
var itemsUrl = "https://sites.sp.kp.org/pub/qosstgcat/_api/web/SiteGroups/getbyid(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor(carootUrl);
executor.executeAsync(
{
url : itemsUrl,
method : "GET",
headers : {"Accept" : "application/json; odata=verbose"},
success : loadTeamNames,
error : errorHandler
}
);
function loadTeamNames(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function(){
var login_name = $(this)[0].LoginName;
});
defer.resolve(results);
}
return defer.promise;
}
result
$.when(getTeamNames(4, global_user),getTeamNames(185, global_user)).done(function () {
console.log(results);
});

Javascript Function Returns Undefined JSON Object (But It's Not Undefined!)

I am trying to return a JSON object from a function using the JSON jQuery plugin (http://code.google.com/p/jquery-json/) but after returning the object from the function, it becomes undefined.
$(document).ready(function() {
var $calendar = $('#calendar');
$calendar.weekCalendar({
...
data : function(start, end, callback) {
var datas = getEventData();
alert(datas); // Undefined???
}
});
If I inspect the object before returning it, it is defined.
function getEventData() {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
//alert(dataString);return false;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
alert($.toJSON(jsonArray)); // Defined!
return ($.toJSON(jsonArray));
} else {
}
}
});
}
Any idea what I'm missing here?
function getEventData() {
function local() {
console.log(42);
return 42;
}
local();
}
Your missing the fact that the outer function returns undefined. And that's why your answer is undefined.
Your also doing asynchronous programming wrong. You want to use callbacks. There are probably 100s of duplicate questions about this exact problem.
Your getEventData() function returns nothing.
You are returning the JSON object from a callback function that's called asynchronously. Your call to $.ajax doesn't return anything, it just begins a background XMLHttpRequest and then immediately returns. When the request completes, it will call the success function if the HTTP request was successful. The success function returns to code internal in $.ajax, not to your function which originally called $.ajax.
I resolved this by using callbacks since AJAX is, after all. Once the data is retrieved it is assigned to a global variable in the callback and the calendar is refreshed using the global variable (datas).
$(document).ready(function() {
// Declare variables
var $calendar = $('#calendar');
datas = "";
set = 0;
// Retrieves event data
var events = {
getEvents : function(callback) {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
//alert($.toJSON(jsonArray));
callback.call(this,jsonArray);
} else {
}
}
});
}
}
$calendar.weekCalendar({
data : function(start, end, callback) {
if(set == 1) {
callback(datas);
//alert(datas.events);
}
}
});
// Go get the event data
events.getEvents(function(evented) {
displayMessage("Retrieving the Lineup.");
datas = {
options : {},
events : evented
};
set = 1;
$calendar.weekCalendar("refresh");
});
});

Categories

Resources