Calculate age via JS (ASP.NET MVC) - javascript

I have this code to get data from back -end
$('#display').click(function () {
var vacancyId = $("#vacancy").val();
var model = {
vacancyId: vacancyId
};
$.ajax({
url: '#Url.Action("Links", "Questions")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
var question2 = data;
for (var i = 0; i <= question2.length - 1; i++) {
var videoHTML = '<div style="width:100%;overflow-y: scroll;background:white;height:72%">' + '<div style="float:left; width:50%;height:296px;border-style:solid;margin-bottom:10px;">' +
'<video style="width:100%;height:290px; object-fit: contain;" controls>';
videoHTML += '<source src="' + document.location.origin + "/uploads/" + question2[i].Linkes + ".webm" + '" type="video/webm">';
videoHTML += '</video>' + '</div>' + '<div style="float:right;width:48%;text-align:center;height:296px;border-style:solid;padding-top:30px;">' + '<div>' + '<b>' + "Ф.И.О: " + '</b>' + '<b>' + question2[i].FIO + '</b>' + '</div>' + '<div>' + '<b>' + "Город: " + '</b>' + '<b>' + question2[i].City + '</b>' + '</div>' + '<div>' + '<b>' + "Город: " + '</b>' + '<b>' + question2[i].Vozrast + '</b>' + '</div>'+'</div>'+'</div>';
$(".videolist").append(videoHTML);
}
}
});
});
This one return date of birthday '<b>' + question2[i].Vozrast + '</b>'
I need to display age.
How I can do this on client-side?

You can do this in server side or client side depend on you.
If you like to do it in client side and Vozrast type is Date, so you can use third libraries to do this e.g. Moment.Js
var years = moment().diff(Vozrast, 'years');
var days = moment().diff(Vozrast, 'days');

I do it like this on client side
var today = new Date();
var yyyy = today.getFullYear();
Get year like this
And get age like this
(yyyy - question2[i].Vozrast)

Related

Getting Tippy Nested ToolTip Displayed

I've been trying to get Tippy.js' nested tooltip feature working but haven't had luck so far.
the following lines are placed outside jQuery's Document ready function:
tippy.setDefaultProps({
appendTo: function () {
return document.querySelector('.responseBody')
}
})
popperOptions: { strategy: 'fixed' };
tippy.delegate('.responseBody', {
target: '.tooltip'
});
the tooltip content is being added dynamically based on an extract from ajax response and the ajax function is the following:
function _loadLaunchPad(iSMHost, iSMPort, urlExtension) {
var _serverName = $('#serverName option:selected').text();
var _addOnSelect = $('#addOnSelect option:selected').text();
var _consoleCmdExprValue = $('#consoleCmdExprValue').val();
var dataString = '{ "serverSelection" : "' + _serverName + '", "operationSelection" : "' + _addOnSelect + '", "commandSelection" : "' + _consoleCmdExprValue + '"}';
var stringToSend = " <img class='preLoader' src='images/preloader.gif' title = 'Processing request'/>";
const _toolTipContentHeader = ' <div>' +
' <strong>Server Name    <span class="tooltip" data-title="<strong>hey</strong>" style="color: aqua">%HDRITEM0%</span></strong><br />' +
' <strong>Server IP Address    <span style="color: aqua">%HDRITEM1%</span></strong><br />' +
' <strong>Server #Processors    <span style="color: aqua">%HDRITEM2%</span></strong><br />' +
' <strong>Version    <span style="color: aqua">%HDRITEM3_1%</span></strong><br />' +
' <strong>Build Ref    <span style="color: aqua">%HDRITEM3_2%</span></strong><br />' +
// ' <strong>Build Date    <span style="color: aqua">%HDRITEM3_3%</span></strong><br />' +
' <strong>Configs Count    <span style="color: aqua">%HDRITEM4%</span></strong><br />' +
' <strong>Master Config    <span style="color: aqua">%HDRITEM5%</span></strong><br />' +
' </div>';
const _toolTipContentLine = ' <div>' +
' <strong>Server Name    <span style="color: aqua">%LNITEM0%</span></strong><br />' +
' <strong>Config Process ID    <span style="color: aqua">%LNITEM1%</span></strong><br />' +
' <strong>Config Status    <span style="color: aqua">%LNITEM2%</span></strong><br />' +
' <strong>Config Java Version    <span style="color: aqua">%LNITEM3%</span></strong><br />' +
' <strong>Version    <span style="color: aqua">%LNITEM4_1%</span></strong><br />' +
' <strong>Build Ref    <span style="color: aqua">%LNITEM4_2%</span></strong><br />' +
// ' <strong>Build Date    <span style="color: aqua">%LNITEM4_3%</span></strong><br />' +
' <strong>iBSE Port (If Enabled)    <span style="color: aqua">%LNITEM5%</span></strong><br />' +
' <strong>Master Config    <span style="color: aqua">%LNITEM6%</span></strong><br />' +
' <strong>Registry    <span style="color: aqua">Here</span></strong><br />' +
' <strong>Blue    <span style="color: aqua">Here</span></strong><br />' +
' <strong>Runtime    <span style="color: aqua">Here</span></strong><br />' +
' </div>';
$.ajax({
type: "POST",
url: `http://${iSMHost}:${iSMPort}/${urlExtension}`,
data: dataString,
timeout: 60000 * 30, //60000 milliseconds * 30 = 30 minutes
async: true,
contentType: "application/json",
cache: false,
beforeSend: function () {
$(".terminal .top").addClass('color-change-5x');
$('.terminal .responseBody').html("");
},
success: function (result) {
if (_addOnSelect == 'ConfigsList') {
var h1 = $('<h1 class="responseTitleText">Launch Pad</h1>')
var tabDiv = $('<div id="tabsID"></div>')
var prodTab = $('<div class="tab-container" data-tab-index="0"></div>');
var testTab = $('<div class="tab-container" data-tab-index="1" style="display:none;"></div>');
$('.terminal .responseBody').append(h1);
$('.terminal .responseBody').append(prodTab);
$('.terminal .responseBody').append(testTab);
for (var i = 0; i < result.length; ++i) {
var div = $('<div>'), ulForTest = $('<ul>'), ulForProd = $('<ul>');
var _tempHeaderItem = result[i];
var _tempInstanceFlag = (_tempHeaderItem.host).split(':')[1];
var _tempHostEnvironment = (_tempHeaderItem.host).split(':')[0]
_tempHostEnvironment = ((/p.me.com$/).test(_tempHostEnvironment)) ? 'Prod' : 'Test';
var replacementsForHDR = {
"%HDRITEM0%": _nvl(_tempHeaderItem.host.replace('.me.com', '')),
"%HDRITEM1%": _nvl(_tempHeaderItem.serverIP),
"%HDRITEM2%": _nvl(_tempHeaderItem.processorsCount),
"%HDRITEM3_1%": _nvl(_tempHeaderItem.configs[0].Version),
"%HDRITEM3_2%": _nvl(_tempHeaderItem.configs[0].Build),
// "%HDRITEM3_3%": _nvl(_tempHeaderItem.configs[0].BuildDate),
"%HDRITEM4%": _nvl(('Active: ' + _tempHeaderItem.activeConfigsCount + '/ Inactive: ' + _tempHeaderItem.inActiveConfigsCount)),
"%HDRITEM5%": _nvl(_tempHeaderItem.master)
};
var _toolTipContentHeaderInstance = _toolTipContentHeader.replace(/%\w+%/g, function (all) {
return replacementsForHDR[all] || all;
});
_tempInstanceFlag = (_tempInstanceFlag == '19') ? '1st' : (_tempInstanceFlag == '29') ? '2nd' : (_tempInstanceFlag == '39') ? '3rd' : (_tempInstanceFlag == '49') ? '4th' : '1st?';
if(_tempHostEnvironment == 'Prod'){
ulForProd.append("<li class='tooltip' data-title='" + _toolTipContentHeaderInstance + "'>" + ((_tempHeaderItem.host).split('.')[0]).replace(".me.com", "") + " " + _tempInstanceFlag + "</li>")
}else{
ulForTest.append("<li class='tooltip' data-title='" + _toolTipContentHeaderInstance + "'>" + ((_tempHeaderItem.host).split('.')[0]).replace(".me.com", "") + " " + _tempInstanceFlag + "</li>")
}
for (var j = 0; j < _tempHeaderItem.configs.length; ++j) {
var _tempLineItem = _tempHeaderItem.configs[j];
var replacementsForLN = {
"%LNITEM0%": _nvl(_tempHeaderItem.host.replace('.me.com', '')),
"%LNITEM1%": _nvl(_tempLineItem.processID),
"%LNITEM2%": _nvl(_tempLineItem.status),
"%LNITEM3%": _nvl(_tempLineItem.javaVersion),
"%LNITEM4_1%": _nvl(_tempLineItem.Version),
"%LNITEM4_2%": _nvl(_tempLineItem.Build),
// "%LNITEM4_3%": _nvl(_tempLineItem.BuildDate),
"%LNITEM5%": _nvl(((_tempLineItem.ibsePort.length > 0) ? _tempLineItem.ibsePort : 'NA')),
"%LNITEM6%": _nvl(_tempHeaderItem.master),
"%LNITEM7%": _nvl('http://' + _tempHeaderItem.host + '/' + _tempLineItem.config + '&filter=on'),
"%LNITEM8%": _nvl('http://' + _tempHeaderItem.host + '/yes?configuration=' + _tempLineItem.config),
"%LNITEM9%": _nvl('http://' + _tempHeaderItem.host + '/yes?configuration%7D_' + _tempLineItem.config)
};
var _toolTipContentLineInstance = _toolTipContentLine.replace(/%\w+%/g, function (all) {
return replacementsForLN[all] || all;
});
if(_tempHostEnvironment == 'Prod'){
div.append(ulForProd.append("<li class='tooltip' data-title='" + _toolTipContentLineInstance + "'>" + _tempLineItem.config + "</li>"));
$('#tabLink').show();
$('.terminal .responseBody .tab-container[data-tab-index=0]').append(div.addClass('tracking-in-expand-fwd'));
}else{
div.append(ulForTest.append("<li class='tooltip' data-title='" + _toolTipContentLineInstance + "'>" + _tempLineItem.config + "</li>"));
$('#tabLink').show();
$('.terminal .responseBody .tab-container[data-tab-index=1]').append(div.addClass('tracking-in-expand-fwd'));
}
}
}
}
tippy('.tooltip', {
theme: 'custom',
content: function (reference) {
const htmlContent = reference.getAttribute('data-title');
return htmlContent;
},
interactive: true,
allowHTML: true,
multiple: true
});
popperOptions: { strategy: 'fixed' };
},
error: function (x, t, m) {
$('.terminal .responseBody').html("<p class='error fade-in-fwd'>Something went wrong at the server. Thats all I know! :-(</p>");
},
complete: function (x, t, m) {
$('.terminal .title').html('response pane');
$(".terminal .top").removeClass('color-change-5x');
}
});
return false;
}
the relevant CSS styling info
.tippy-box[data-theme~="custom"] span {
float: right;
}
.tippy-box[data-theme~="custom"] {
width: max-content;
}
Owing to the complexity of the application, I couldn't create a repro on a fiddle/etc. The first tooltip gets displayed well, while the nested does not get displayed.
result:
Any help would be much appreciated.
If the nested tooltip is invoked using data-tippy-content with html, the value gets displayed but the HTML gets displayed raw, meaning, HTML tags appear as-is.

give multiple params for a tag onclick function in JSP

I use a tag onclick function to delete specific documents.
I call the function with three arguments.
but my regex does not include a specific case.
Generally, it works, like "test".
but some case doen't work.
Like this case => "St. John's"
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item);
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + "\"" + value + "\"" + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
});
this is expected key value example
const key = "en";
const value = "test"; // it works
const value = "St. John's"; // it doesn't work.
const regionCode = "AG-ANU";
if onclick function call success,
it calls this function
function deleteName(key, value, regionCode) {
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + key + "&name=" + value,
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
I need help for value part regex expression.
It is not good way, but I solved like this.
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item)[0];
var valueStr = JSON.stringify(value);
var valueString = value.replace(/'/gi, "\\\'");
var keyValueRegionCode = key + "|" + valueString + "|" + regionCode;
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '[ 삭제 ]' + '</td></tr>';
});
then calls keyValueRegionCode
function deleteName(keyValueRegionCode) {
var keyValue = keyValueRegionCode.split("|")[0];
var nameValue = keyValueRegionCode.split("|")[1];
var regionCode = keyValueRegionCode.split("|")[2];
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + keyValue + "&name=" + encodeURIComponent(nameValue),
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
1) value.replace(/'/gi, "\\'"); -> this regex makes single apostrophe like this. (\')
2) make parameters one for calling function easily .

If a change a Javascript string links on a page don't work, and I don't know why?

I've got a JavaScript file querying a SharePoint list. It's working great but returning an 'undefined' line which I can't resolve:
Fine, so I thought I'd just knock it out from the code.
If I use this string:
txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalog‌​ue%20Devices.aspx?di‌​d=" + tempID + "'>" + tempTitle + "</a>" + "</p>";
The undefined vanishes BUT none of the links work, despite being the exact same links if I use this string which shows up the 'undefined'?!
txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=" + tempID + "'>" + tempTitle + "</a> - " + tempDeviceType + "</p>";
This is an example of a link: http://example.com/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=10
The code for the two js files I'm using (getDevices and getDeviceDetails) are below:
getDevices
function getDevices() {
var txtTitle = "";
var txtDeviceType = "";
var query = "http://example.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc/Devices?select=ID,Title";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function (i, result) {
var tempID = result.Id;
var tempTitle = result.Title;
var tempDeviceType = result.DeviceTypeValue;
txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=" + tempID + "'>" + tempTitle + "</a> - " + tempDeviceType + "</p>";
//txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalog‌​ue%20Devices.aspx?di‌​d=" + tempID + "'>" + tempTitle + "</a>" + "</p>";
});
$('#devices').append($(txtTitle));
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
getDeviceDetails
function getDeviceDetails() {
var txtTitle = "";
var txtName = "";
var txtOverview = "";
var txtAccessories = "";
var txtDevicetype = "";
var txtTypicalDeviceUsage ="";
var txtKnownSystemIssues ="";
var txtTrafficlight = "";
var imgDevicePicture = "";
var tempLCS2 = "";
var HTML = "<h3>Desktop</h3>";
var Laptop = "Y"
var Tabs="Y" ;
var query
= "http://example.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc/Devices?$expand=Priority&$filter=Id eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
var tempID = item.Id;
var NameofDevice = item.Title;
var tempTitle = item.Title;
var DeviceOverView = item.Description;
var AccessDetails = item.Accessories;
var DeviceKind = item.DevicetypeValue;
var Usage = item.TypicalUsage;
var DevicePriority = item.PriorityValue;
var DeviceImage = item.DeviceImage;
txtTitle = "<p>";
txtName = "<p>" + NameofDevice + "</p>" + DeviceKind + "</p>";
txtOverview = "<p>" + DeviceOverView + "</p>";
txtAccessories = "<p>" + AccessDetails + "</p>";
txtDevicetype = "<p>" + DeviceKind + "</p>";
txtTypicalDeviceUsage = "<p>" + Usage + "</p>";
txtTrafficlight = "<p>" + DevicePriority + "</p>";
imgDevicePicture = "<img src='" + DeviceImage + "'>";
});
$('#devicedetails').append($(txtTitle));
$('#deviceoverview').append($(txtOverview));
$('devicename').append(txtName);
$('#devicekind').append(txtDevicetype);
$('#deviceacc').append(txtAccessories);
$('#deviceuse').append(txtTypicalDeviceUsage);
$('#devicestatus').append(txtTrafficlight);
$('#imageContainer').append("<img src='/sites/IT/ITInfrastructure/SiteAssets/"+txtTrafficlight.replace(/<[^>]*>/g, '')+".png' />");
$('.deviceimage').append(imgDevicePicture);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
You have some charset problem. When I copy paste the lines:
txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=" + tempID + "'>" + tempTitle + "</a> - " + tempDeviceType + "</p>";
//txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalog‌​ue%20Devices.aspx?di‌​d=" + tempID + "'>" + tempTitle + "</a>" + "</p>";
In notepadd++ with ANSI encoding, I get:
txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=" + tempID + "'>" + tempTitle + "</a> - " + tempDeviceType + "</p>";
//txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalog??ue%20Devices.aspx?di??d=" + tempID + "'>" + tempTitle + "</a>" + "</p>";
Notice the "??" in the "Service%20Catalogue%20Devices" and "did" part. I think this is what make your link fail.
This worked at knocking out the 'undefined':
txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=" + tempID + "'>" + tempTitle + "</a></p>";

html code in javascript not getting the id to open to another window

I have a html inside a javascript. My problem is I cant call the id in my html code. Can someone help me with this?
My code:
<script type= "text/javascript">
// customer notification
notifications.initMenu({
projects: '#projects1'
});
$.getJSON('/Customer/ForCustomerNotif' + '?userId=' + userId, function (savedCusNotif) {
$.each(savedCusNotif, function () {
var ID = this["ID"];
var workerId = this["WorkerID"];
var Name = this["Name"];
var DateApplied = this["DateCreated"];
var Position = this["Position"];
var Read = this["IsRead"];
var WorkerID = this["WorkerID"];
var ClientCusId = this["Client_CustomerID"];
var positionId = this["PositionID"];
var options = (Read == true) ? {
id: ID,
unread: 'unread',
category: "projects",
message: '<b>' + Name + '</b>' + '<br/>' + " is applied in the " + '<b>' + Position + '</b>' + " " + "position" + " on " + '<br/>' + DateApplied + "."
} : {
id: ID,
read: 'read',
category: "projects",
message: '<b>' + Name + '</b>' + '<br/>' + " is applied in the " + '<b>' + Position + '</b>' + " " + "position" + " on " + '<br/>' + DateApplied + "."
//im calling this link for redirection in another window.
+'View '
};
notifications.createNotification(options);
// I tried to call the id but doesn't work.
$("#redirect").click(function() {
alert("get link");
var redirect = $(this).attr('href', '/Customer/ViewAppliedWorkersProfile?workerId=' + WorkerID + '&positionId=' + positionId + '&positionIds=' + positionId);
window.open(redirect, 'width=900,height=800,left=190,top=100,screenX=190,screenY=100,resizable=no,resizable=0,resizable=false,scrollbars=yes');
});
});
});
</script>
I'm using ttwnotificationmenu.js from www.codebasehero.com.
So my problem is getting the id in the html code hope someone will help me with this.

Recieving JSON from AJAX Call with MongoDB

I am getting a users details from a MongoDB database like this:
$user=$collection->findOne(array('_id' => new MongoId($_SESSION['user']['userid'])));
if (!empty($user)){
json_encode($user);
print_r($user);
}
I can get an entire JSON array from the AJAX but not individual elements - I get undefined:
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
alert(msg);
}
});
The actual JSON is structured like this:
username: john
password: hello
email: me#mailserver.com
I'm stuck.
you returning array object from getUser.php but you display it as a normal variable
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
$.each(msg,function(key,value){
alert(value.id);
});
}
});
i guess this will work..
You need to get the return value
$encoded = json_encode($user);
print_r($encoded);
The method you are using does not encode in place. It returns a left side value.
success: function (response)
{
if(response != 'error')
{
//parse into JSON
var jsonObj = JSON.parse(response);
var HTML = '';
//extract single value using each
$.each(jsonObj, function(key, val) {
HTML += '<tr><td>' + val.id + '</td><td>' + val.first_name + '</td><td>' + val.last_name + '</td><td>' + val.gender + '</td>'
+'<td>' + dt + '</td><td>' + val.phone + '</td><td>' + val.mobile + '</td><td>' + val.email + '</td>'
+'<td>' + val.address + ',' + val.city + ',' + val.state + '</td><td>' + val.country + '</td>'
+'<td>' + val.zip + '</td><td>' + val.hobbies + '</td><td>' + 'INR ' +val.salary + '</td><td>' + val.countryCode + '</td>'
+'<td>' + val.username + '</td><td>' + val.pwd + '</td></tr>';
});

Categories

Resources