I am calling a webapi using get method which will give json data and I am display as a table from that data. the code which I have given below is working fine. I got around 25 rows(dynamically" of data when I fit the service. this webpage will be refreshed using signalR. when any changes in DB immediately it should reflect in the webpage.
My question is if "" + item.TakeupType + "" value is "Completed" or "cancelled" this row background should change to gray color and after 2mins row should be remove from the webpage.
Note:
1) Only 22 rows should display on webpage in orderby asc Datetime.
2) Completed/cancelled items from DB should will display on the webpage for 2 mins and drop off.
My code :
Hide Expand Copy Code
//Webapi call - To load info status.
function LoadinfoStatus() {
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('x-api-key', '9024024A-024-485C024-6BC2024DA');
}
});
$.ajax({
type: "GET",
url: "https://mywebsites.net/version1/info/494",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
//Function to get DateFormat
function getFormattedDate(date) {
// debugger;
var inputdate = new Date(date);
var currentdate = new Date();
var strTime = getFormattedTime(inputdate);
var rngStrTime = getFormattedTime(add_minutes(inputdate, 5));
if (inputdate > currentdate) {
return inputdate.getDate() + '/' + (inputdate.getMonth() == 0 ? 12 : inputdate.getMonth()) + " " + strTime + " - " + rngStrTime;
}
else {
return strTime + " - " + rngStrTime;
//return day + "/" + month + " - " + strTime;
}
}
var add_minutes = function (dt, minutes) {
return new Date(dt.getTime() + minutes * 60000);
}
function getFormattedTime(inputdate) {
var day = inputdate.getDate();
var month = inputdate.getMonth() + 1;
var hours = inputdate.getHours();
var minutes = inputdate.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
return hours + ':' + minutes + ampm;
}
$.each(data, function (i, item) {
var rows = "<tr ' " + (item.Count > 100 ? "data-id='" + item.orderId + "'" : "") + (item.TakeupType == "Cancelled" ? "style='background-color: gray; color: white'" : "") + " align= 'center' > " +
"" + "" + "" + "" +
"" + item.user.firstName + " " + item.user.lastName.charAt(0) + "." + "" +
"" + item.TakeupType + "" +
"" + (item.Count == undefined ? "$" + " " + 0 : "$" + " " + item.Count) + "" +
"" + getFormattedDate(item.TakeupTimeUtc) + "" +
"= 100 ? "style='background-color: darkorange; color: white'>***" : ">") + "" +
"";
var $tbody = $('tblOrders tbody');
$('#tblOrders').append(rows);
}); //End of foreach Loop
registerEvents();
// console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
}
Related
Javascript we had for Unified interface of Dynamics 365 to format phone numbers was working perfectly until the latest update, now it only works in custom interface and has stopped working in UI, anybody has any idea how this can be fixed?
var XXX = window.XXX || {};
(function() {
// Code to run in the form OnLoad event
this.formOnLoad = function(executionContext) {
var formContext = executionContext.getFormContext();
// display the form level notification as an INFO
formContext.ui.setFormNotification(message, "INFO", myUniqueId);
// Wait for 5 seconds before clearing the notification
window.setTimeout(function() {
formContext.ui.clearFormNotification(myUniqueId);
}, 5000);
}
// Code to run in the attribute OnChange event
this.mobilePhoneFormatting = function(executionContext) {
var formContext = executionContext.getFormContext();
var mobilePhone = formContext.getAttribute("mobilephone").getValue();
var formatPhone = "";
try {
if (mobilePhone != null) {
var phoneNumbers = mobilePhone.replace(/\D/g, '');
if (phoneNumbers.length == 10) { //10 digit case. Output adds +1 and proper format
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10));
} else if (phoneNumbers.length == 11) { //11 digit case. Output proper format
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11));
} else if (phoneNumbers.length == 14) { //14 digit case. Without Country code and with extension
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10) + " x" + phoneNumbers.substring(10, 14));
} else if (phoneNumbers.length == 15) { //15 digit case. With Country code and extension
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11) + " x" + phoneNumbers.substring(11, 15));
} else if (phoneNumbers.length == 4) { //4 digit case. Extension Only
formatPhone = ("x" + phoneNumbers.substring(0, 4));
} else {
formatPhone = mobilePhone;
}
formContext.getAttribute("mobilephone").setValue(formatPhone);
formContext.data.entity.save();
}
} catch (err) {
txt = "There was an error formatting the Phone Number.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
I'm using openweathermap for my application https://openweathermap.org/current and I need to input the current time with weather in the city.
The time in the API in UNIX format. How I can input the time in application in normal format (h:m:s)
Line with date/time from API (dt....Time of data calculation, unix, UTC)
Below my JS code
document.querySelector('#city').addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var city = $(this).val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
});
} else {
$("#error").html("<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>");
}
};
});
function show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Pressure</strong>: " + data.main.pressure + "hPa</h3>" +
"<h3><strong>Humidity</strong>: " + data.main.humidity + " %</h3>" +
"<h3><strong>Min. Temperature</strong>: " + data.main.temp_min + "°C</h3>" +
"<h3><strong>Max. Temperature</strong>: " + data.main.temp_max + "°C</h3>" +
"<h3><strong>Wind Speed</strong>: " + data.wind.speed + "m/s</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}
If you mean letting the user input some date+time in local format and getting UNIX timestamp for it, you can use Date.parse(), just it returns the milliseconds while you need seconds, so divide the result with 1000. (The base date+time is the same for both, 1970 Jan 1. 00:00:00 UTC)
function doConvert(event){
unix.textContent=Math.round(Date.parse(event.target.value)/1000);
}
<input type="datetime-local" onchange="doConvert(event)"><br>
<div id="unix"></div>
If you mean the other way around (UNIX time to readable), use Date() (remember to convert seconds to milliseconds) and its toLocaleString():
function doConvert(event){
time.textContent=new Date(event.target.valueAsNumber*1000).toLocaleString();
}
<input type="number" oninput="doConvert(event)"><br>
<div id="time"></div>
UnixTime = https://en.wikipedia.org/wiki/Unix_time
var UnixTime = 1525478400;
var myDate = new Date(UnixTime*1000);
var HH = myDate.getHours();
var MM = myDate.getMinutes();
var SS = myDate.getSeconds();
document.write(HH+":"+MM+":"+SS);
I am trying to code chat box with ajax, but when I make the call, the php file shatbox.php doesn't appear. Here is the code and the GitHubDiff.
GitHubb Diff
$(document).ready(function(){
$('#submit').on('click',function(){
var name = $('#name').val();
var shout = $('#shout').val();
var date = getDate();
var dataString = 'name=' + name + '&shout=' + shout + '&date' + date;
// validation
if(name == '' || shout == ''){
alert('please fill Your name and shout');
}else{
$.ajax({
type:"POST",
url:"../jschat/shoutbox.php",
data: dataString,
cache: false,
success: function(html){
$('#shout ul').prepend(html);
}
});
}
return false ;
});
});
function getDate(){
var date;
date = new date;
date = date.getUTCFullYear() +'-'+
('00' + (date.getUTCMonth() +1 )).slice(-2)+'-'+
('00' + date.getUTCDate().slice(-2)+' '+
('00' + date.getUTCHours().slice(-2)+ ':'+
('00' + date.getUTCMinutes().slice(-2)+':'+
('00' + date.getUTCSeconds().slice(-2);
return date;
}
There are 2 errors in the function getDate:
1.Date object is case-sensitive
2.There are some missing closing parentheses starting from date.getUTCMonth
function getDate() {
var date = new Date;
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth() + 1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
return date;
}
This may be the cause of your issue.
file location seems to be the issue
url:"../jschat/shoutbox.php",
try this
url:"../shoutbox.php",
i'm coding a jquery clock plugin, it works correctly but i can't have more than 1 clock for page, the old version works correctly with infinite numbers of clock for page, but is not a JQ plugin, so whats wrong?
New code:
(function( $ ) {
function time() {
d = new Date();
day = {
h: d.getHours(),
m: d.getMinutes(),
s: d.getSeconds(),
ms: d.getMilliseconds()
};
function check(i) {
if (i < 10) {i = "0" + i;}
return i;
}
day.h = check(day.h);
day.m = check(day.m);
day.s = check(day.s);
t = day.h + ":" + day.m + ":" + day.s + ":" + day.ms;
tNoMs = day.h + ":" + day.m + ":" + day.s;
hexTime = '#' + day.h + '' + day.m + '' + day.s;
}
$.fn.newClock = function ( options ) {
opt = $.extend({
ms: false,
type: 'classic'
}, options );
element = $(this);
setInterval(function () {
time();
switch (opt.ms) {
case true:
time();
element.html(t);
break;
case false:
switch (opt.type) {
case 'classic':
time();
element.html(tNoMs);
break;
case 'hex':
time();
element.html(hexTime);
break;
}
break;
}
}, 1);
};
} ( jQuery ) );
Old version:
function Clock() {
function temp() {
d = new Date();
day = {
h: d.getHours(),
m: d.getMinutes(),
s: d.getSeconds(),
ms: d.getMilliseconds()
};
day.h = check(day.h);
day.m = check(day.m);
day.s = check(day.s);
day.ms = check(day.ms);
function check(i) {
if (i < 10) {i = "0" + i;}
return i;
}
t = day.h + ":" + day.m + ":" + day.s + ":" + day.ms;
tNoMs = day.h + ":" + day.m + ":" + day.s;
hexTime = '#' + day.h + '' + day.m + '' + day.s;
}
temp();
this.new = function (selector, tf, type) {
function getStatus(variable) {
if (variable === true) {
return variable;
} else {
return variable;
}
}
setInterval(function () {
temp();
if (tf === true) {
$(selector).html(t);
} else {
$(selector).html(tNoMs);
}
if (type === true) {
$(selector).html(hexTime);
}
}, 1);
};
}
Thanks in advance..
your are sharing your javascript variables as global that are overwriting each other.
$.fn.newClock = function ( options ) {
var opt = $.extend({
ms: false,
type: 'classic'
}, options );
var element = $(this);
You are sharing variables t, tNoMs, hexTime. And, the most important, element and opt! I've hide it in the newClock() method. So this should work:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
(function( $ ) {
$.fn.newClock = function ( options ) {
var t, tNoMs, hexTime, element; // here we making this variables local to current jQuery object
function time() {
d = new Date();
day = {
h: d.getHours(),
m: d.getMinutes(),
s: d.getSeconds(),
ms: d.getMilliseconds()
};
function check(i) {
if (i < 10) {i = "0" + i;}
return i;
}
day.h = check(day.h);
day.m = check(day.m);
day.s = check(day.s);
t = day.h + ":" + day.m + ":" + day.s + ":" + day.ms;
tNoMs = day.h + ":" + day.m + ":" + day.s;
hexTime = '#' + day.h + '' + day.m + '' + day.s;
}
// opt must be local too
var opt = $.extend({
ms: false,
type: 'classic'
}, options );
element = this; //you don't need here $(this)
var timer = setInterval(function () {
time();
switch (opt.ms) {
case true:
time();
element.html(t);
break;
case false:
switch (opt.type) {
case 'classic':
time();
element.html(tNoMs);
break;
case 'hex':
time();
element.html(hexTime);
break;
}
break;
}
}, 1);
};
} ( jQuery ) );
$(function() {
$('#c1').newClock({type: 'classic'});
$('#c2').newClock({type: 'hex'});
});
</script>
</head>
<body>
<div id="c1"></div>
<div id="c2"></div>
</body>
</html>
I have tried many ways to make a live clock (with seconds) appear in a rendered table but it's not working propperly. The clock stays static, not showing second by second. I'm doing the following :
function myTable(){
var table = $('<table></table>');
table.append($('<tr>')
.append($('<td>')
.addClass('col2 data')
.attr('rowspan', '2')
.append($('<span>')
.attr('id', 'date_time')
)
)
)
$("#myDiv").html(table)
}
liveClock();
var liveClock = function () {
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
var setDateTime = function() {
$("#date_time").html(result);
return false;
};
var everySec = setInterval(setDateTime, 1000);
}
Your problem is that you're never updating result, so each time your code fires SetDateTime, it renders the same date in the table. Move these lines:
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
Into your setDateTime function.