I have the following Jquery script that calculates the number of days between two dates and changes the color of the cell according to the time left.
Now, the calculation works but what it doesn't work all the times is that when I open the tab where this information is displayed most of the times the first time I open it, it works but then if I click on it again or if I click on another tab, it won't display the change of color.
<script>
function expiryDates() {
var warning = "<?php echo config('WARNING_DATE')?>";
var critical = "<?php echo config('CRITICAL_DATE')?>";
//gets and creates array of all TD 'lod' dates
var expDate = "<?php echo $content['lod'] ?>";
//var value = $(this).text();
expDate = expDate.split("-");
//Gets today's date and formats it to MYSQL date format
var now = (new Date()).toISOString().substring(0, 10);
now = now.split("-");
//Converts all TD dates into days
var eDate = new Date(expDate[0] + "-" + expDate[1] + "-" + expDate[2]);
//Converts today's date into day
var sDate = new Date(now[0] + "-" + now[1] + "-" + now[2]);
//Does the math
var daysApart = Math.abs(Math.round((sDate - eDate) / 86400000));
//Changes cells color
if (daysApart < critical) {
//$("#expiration-date").addClass('expired');
$("#expiration-date").css("color", "red");
} else if ((daysApart > critical) && (daysApart <= warning)) {
$("#expiration-date").css("color", "#orange");
// $("#expiration-date").addClass('about_expired');
} else if (eDate < sDate) {
$("#expiration-date").css("color", "red");
// $("#expiration-date").addClass('expired');
}
}
</script>
I have used as well:
$( document ).ready( expiryDates);
and
$( window ).on( "load", expiryDates);
but the result is the same.
Any input would be appreciated.
Thank you!
Edit:
Sorry for the missing information.
The way this is setup, is that I have a main blade that calls this information tab:
The main blade has this code:
<td class="detail-slide-specifications" id="detail-slide-specifications{{ $item['mainHwID'] }}" onclick="showSpecifications({{ $item['mainHwID'] }})">
and this is the AJAX call:
function showSpecifications(masterID)
{
var itemID = "#detail-panel-specs" + masterID ;
var loadingImgClass = ".specifications_loading_spinner_" + masterID ;
if (masterID == "") {
$(itemID).html( "Error : No Master ID");
return;
} else {
var request = $.ajax({
url: "get_specifications?masterID=" + masterID,
type: "get",
timeout: 5000
});
request.done(function (responseText) {
$(loadingImgClass).hide();
$(itemID).html(responseText);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
$(loadingImgClass).hide();
$(itemID).html("Error " + errorThrown);
});
}
}
Related
So I am trying to store the date inside a database and to do so I need to pass the variable 'date' to the PHP file store.pro.php however, I am not sure how to do this. I have tried Ajax but at the moment it doesn't seem to be working.
Javascipt code:
// variables for fetching current date
n = new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
// variables for displaying current date
let displayDay = 0;
let displayMonth = 0;
// If m or d are only one digit, add a leading 0 to the value
if (d < 10) {
displayDay = '0' + d.toString();
} else {
displayDay = d.toString();
}
if (m < 10) {
displayMonth = '0' + m.toString();
} else {
displayMonth = m.toString();
}
// storing the current date within raceDate
var date = displayDay + '/' + displayMonth + '/' + y;
$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date }
});
PHP code in store.pro.php
if (isset($_POST['x'])) {
$raceDate = $_POST['x'];
echo($raceDate);
} else {
echo "no";
}
How do you know "it doesn't seem to be working" ?
add success method to your ajax, like this:
$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date },
success: function(res) {
res = JSON.parse(res);
console.log(res);
}
});
Then, in store.pro.php put this:
if (isset($_POST['x'])) {
$raceDate = $_POST['x'];
echo json_encode($raceDate);
} else {
echo json_encode("no");
}
exit; // You may need remove this line, after you check, that ajax call is working
and check console in your browser
I'm using a tableau web connector to download stock price. The source code is following:
<html>
<meta http-equiv="Cache-Control" content="no-store" />
<head>
<title>Stock Quote Connector-Tutorial</title>
<script src="https://connectors.tableau.com/libs/tableauwdc-1.1.1.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function() {
function buildUri(tickerSymbol, startDate, endDate) {
var startDateStr = getFormattedDate(startDate);
var endDateStr = getFormattedDate(endDate);
var queryStatement = 'select * from yahoo.finance.historicaldata where symbol = "' +
tickerSymbol +
'" and startDate = "' + startDateStr +
'" and endDate = "' + endDateStr + '"';
var uri = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(queryStatement) +
"&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json";
return uri;
}
function getFormattedDate(date) {
// Return a date in the format YYYY-MM-DD
return date.getUTCFullYear() +
'-' +
makeTwoDigits(date.getUTCMonth() + 1) +
'-' +
makeTwoDigits(date.getUTCDate());
}
function makeTwoDigits(num) {
// Pad a digit to be two digits with leading zero
return num <= 9 ? "0" + num.toString() : num.toString();
}
var myConnector = tableau.makeConnector();
myConnector.getColumnHeaders = function() {
var fieldNames = ['Ticker', 'Day', 'Close'];
var fieldTypes = ['string', 'date', 'float'];
tableau.headersCallback(fieldNames, fieldTypes);
}
myConnector.getTableData = function(lastRecordToken) {
var dataToReturn = [];
var hasMoreData = false;
// Get parameter values and build YQL query
var ticker = tableau.connectionData;
var endDate = new Date();
var startDate = new Date();
startDate.setYear(endDate.getFullYear() - 1);
//startDate.setYear(startDate.getFullYear() - 1);
//startDate.setYear(startDate.getFullYear() - 1);
//startDate.setYear(startDate.getFullYear() - 1);
var connectionUri = buildUri(ticker, startDate, endDate);
var xhr = $.ajax({
url: connectionUri,
dataType: 'json',
success: function (data) {
if (data.query.results) {
var quotes = data.query.results.quote;
var ii;
for (ii = 0; ii < quotes.length; ++ii) {
var entry = {'Ticker': quotes[ii].Symbol,
'Day': quotes[ii].Date,
'Close': quotes[ii].Close};
dataToReturn.push(entry);
}
tableau.dataCallback(dataToReturn, lastRecordToken, false);
}
else {
tableau.abortWithError("No results found for ticker symbol: " + ticker);
}
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.log("Connection error: " + xhr.responseText + "\n" + thrownError);
tableau.abortWithError("Error while trying to connect to the Yahoo stock data source.");
}
});
}
tableau.registerConnector(myConnector);
})();
$(document).ready(function() {
$("#submitButton").click(function() {
var tickerSymbol = $('#ticker').val().trim();
if (tickerSymbol) {
tableau.connectionName = "Stock Data for " + tickerSymbol;
tableau.connectionData = tickerSymbol;
tableau.submit();
}
});
});
</script>
</head>
<body>
<p>Enter a stock ticker symbol: <input type="text" id="ticker" /></p>
<p><button type="button" id="submitButton">Get the Data</button></p>
</body>
</html>
The code is workable when we just want to download 1 year data, but if we change the time longer than 1 year(enddate.year - startdate.year > 1), it is not workable.
After debugging the code, I found the issue comes from YQL query:
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.historicaldata where symbol = "AAPL" and startDate = "2014-08-24" and endDate = "2016-11-23"&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json
when startDate = "2014-08-24" and endDate = "2016-11-23" is longer than 15 month, YQL will return null. I'm trying to fix this issue. If it is python or java, the problem is not hard, first check whether the duration is longer than 1 year, if so, get 1 year result and do the same for rest n-1 year. But this tableau code makes me stuck with it. I have to make the code workable with tableau, which makes me unable to proceed due to lack of knowledge about both js and tableau.
Can any one advise on this issue? My objective is to make the code workable for >10 years for stock symbol like AAPL.
Thanks in advance.
I don't believe YQL supports queries for longer than 15 months or so. Limits like these are fairly common when working with APIs. What you want to do from a web data connector standpoint is to implement paging.
The high level idea is that your getTableData function of your WDC will execute multiple times, and each time, it will gather a single page of data, which is then passed to Tableau. For example, here's how you could get multiple years worth of data in your example:
myConnector.getTableData = function(lastRecordToken) {
var dataToReturn = [];
var hasMoreData = false;
// Get parameter values and build YQL query
var ticker = tableau.connectionData;
var endDate = new Date();
var startDate = new Date();
var maxYear = 5;
var yearOffset = lastRecordToken || 0;
endDate.setYear(endDate.getFullYear() - (yearOffset));
startDate.setYear(endDate.getFullYear() - 1);
var connectionUri = buildUri(ticker, startDate, endDate);
var xhr = $.ajax({
url: connectionUri,
dataType: 'json',
success: function (data) {
if (data.query.results) {
var quotes = data.query.results.quote;
var ii;
for (ii = 0; ii < quotes.length; ++ii) {
var entry = {'Ticker': quotes[ii].Symbol,
'Day': quotes[ii].Date,
'Close': quotes[ii].Close};
dataToReturn.push(entry);
}
var hasMoreData = !(yearOffset == maxYear);
tableau.dataCallback(dataToReturn, yearOffset + 1, hasMoreData)
}
else {
tableau.abortWithError("No results found for ticker symbol: " + ticker);
}
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.log("Connection error: " + xhr.responseText + "\n" + thrownError);
tableau.abortWithError("Error while trying to connect to the Yahoo stock data source.");
}
});
}
tableau.registerConnector(myConnector);
})();
This example uses the two extra parameters of the dataCallback function to implement paging. The documentation for paging in v1 of the web data connector API can be found here: http://onlinehelp.tableau.com/current/api/wdc/en-us/help.htm#WDC/wdc_paging.htm%3FTocPath%3DAdditional%2520Concepts%7C_____2
Additionally, if you are able to use v2 of the WDC API (usable in Tableau 10 and later), I would highly recommend it. The paging model in V2 is more flexible and easier to use.
Where I'm At
I'm making a form for an online silent auction. People click a button, choose one of six fixed amounts $10, $25, $50, $100, $250, $500 and that amount gets added to the last bid, giving us total amount of their new bid.
Problem
It takes an extraordinarily long time (4-5 seconds after the button is clicked) to replace the tk-amount placeholder using.html to .current__amount and .new__amount and display these two pieces of data grabbed from a Google Spreadsheet using an AJAX call to the SheetsU API.
I have a feeling it's because of how much stuff is being done everytime a button is clicked. Is there a better way to approach this?
scripts.js
// Bid Options
$(".button__form").on('click', function(){
var btnSelected = $(this).hasClass("is-selected");
var sectionOneCompleted = $(".check--one").hasClass("is-completed");
if (btnSelected) {
$(this).removeClass("is-selected");
$(".check--one").css("color", "#ccc");
} else {
$(".button__form").removeClass("is-selected");
$(this).addClass("is-selected");
$(".check--one").css("color", "#ffdc00");
}
});
$(".button__form").on("click", function() {
var lastbtnClicked = ($(this).attr("class"));
// Bid Options
var buttonOne = $(this).hasClass("button__one");
var buttonTwo = $(this).hasClass("button__two");
var buttonThree = $(this).hasClass("button__three");
var buttonFour = $(this).hasClass("button__four");
var buttonFive = $(this).hasClass("button__six");
var buttonSix = $(this).hasClass("button__six");
// Bid Values
var buttonOneValue = 10;
var buttonTwoValue = 25;
var buttonThreeValue = 50;
var buttonFourValue = 100;
var buttonFiveValue = 250;
var buttonSixValue = 500;
/*-------------------------------------
API: SHEETSU
--------------------------------------*/
$.ajax({
url: "https://sheetsu.com/apis/4a8eceba",
method: "GET",
dataType: "json"
}).then(function(spreadsheet) {
// Get and print data
var currentBid = parseInt(spreadsheet.result.pop().Bids);
console.log(currentBid);
var phoneNumber = "1" + spreadsheet.result.pop()["Phone Number"];
var printBid = $(".current__amount").html("$" + currentBid);
console.log(printBid);
if (buttonOne) {
$(".new__amount").html("$" + (currentBid + buttonOneValue));
} else if (buttonTwo) {
$(".new__amount").html("$" + (currentBid + buttonTwoValue));
} else if (buttonThree) {
$(".new__amount").html("$" + (currentBid + buttonThreeValue));
} else if (buttonFour) {
$(".new__amount").html("$" + (currentBid + buttonFourValue));
} else if (buttonFive) {
$(".new__amount").html("$" + (currentBid + buttonFiveValue));
} else if (buttonSix) {
$(".new__amount").html("$" + (currentBid + buttonSixValue));
}
});
});
Are you sure your "performance issues" arn't actually caused by your http request taking 4-5 seconds to complete? To check open your browsers console and click on the network tab. Then press your button. You should see a request send out and how long it takes to complete.
Lets go one by one
Take these out of callback, no need to reinitialize for every click.
// Bid Values
var buttonOneValue = 10;
var buttonTwoValue = 25;
var buttonThreeValue = 50;
var buttonFourValue = 100;
var buttonFiveValue = 250;
var buttonSixValue = 500;
Reduce below
$(".button__form").on('click', function(){
var btnSelected = $(this).hasClass("is-selected");
var sectionOneCompleted = $(".check--one").hasClass("is-completed");
if (btnSelected) {
$(this).removeClass("is-selected");
$(".check--one").css("color", "#ccc");
} else {
$(".button__form").removeClass("is-selected");
$(this).addClass("is-selected");
$(".check--one").css("color", "#ffdc00");
}
});
to this
$(".button__form").on('click', function(){
$(this).toggleClass("is-selected");
$(".check--one").toggleClass("is-completed");
});
//And adjust the color of .check--one in css
And use the class property efficiently
if (buttonOne) {
$(".new__amount").html("$" + (currentBid + buttonOneValue));
} else if (buttonTwo) {
$(".new__amount").html("$" + (currentBid + buttonTwoValue));
} else if (buttonThree) {
$(".new__amount").html("$" + (currentBid + buttonThreeValue));
} else if (buttonFour) {
$(".new__amount").html("$" + (currentBid + buttonFourValue));
} else if (buttonFive) {
$(".new__amount").html("$" + (currentBid + buttonFiveValue));
} else if (buttonSix) {
$(".new__amount").html("$" + (currentBid + buttonSixValue));
}
to something like this in for loop
$(".new__amount."+buttons[i].class).html("$" + (currentBid + buttons[i].value));
var buttons = [{class:"buttonSix", value:123},....]
So at last your code could look like this.
// Bid Options
var buttons = [{class:"buttonOne", value:12},....{class:"buttonSix", value:123}]
$(".button__form").on('click', function(){
$(this).toggleClass("is-selected");
$(".check--one").toggleClass("is-completed");
//And adjust the color of .check--one in css
var lastbtnClicked = ($(this).attr("class"));
/*-------------------------------------
API: SHEETSU
--------------------------------------*/
$.ajax({
url: "https://sheetsu.com/apis/4a8eceba",
method: "GET",
dataType: "json"
}).then(function(spreadsheet) {
// Get and print data
var currentBid = parseInt(spreadsheet.result.pop().Bids);
console.log(currentBid);
var phoneNumber = "1" + spreadsheet.result.pop()["Phone Number"];
var printBid = $(".current__amount").html("$" + currentBid);
console.log(printBid);
var $btnForm = $(".button__form")
for(){
if($btnForm.hasClass(buttons[i].class)){
$(".new__amount.").html("$" + (currentBid + buttons[i].value));
}
}
});
});
I have the following code which will refresh my web part every 60 seconds and its working great. The problem I have is that on top of the refresh code I also have a script that will highlight certain parts of my data and as soon as the refresh kicks in it breaks my scripts. What will happen is I load the page and I can see my script doing its thing my highlighting my data, a minute later the highlights are gone leaving me with just my data. I removed my refresh code and confirmed that my scripts stays intact afterwards.
Reload code:
<script type="text/javascript">
function reload() {
$.ajax({
async: false,
cache:false,
url: "http://ensemble-mtl.ent.cginet/sites/SERVIPCManagement/imc/Shared%20Documents/Whiteboard/Whiteboard.aspx",
complete: function (xData, Status) {
var DVWPMarkup = $(xData.responseText).find("#reload_me").html();
$("#reload_me").html(DVWPMarkup);
}
});
}
$(document).ready(function(){
reload();
var auto_refresh = setInterval(function(){reload();}, 60000);
});
</script>
Highlighting code:
<script language="javascript" type="text/javascript">
$('.IM_last_modified').each(function () {
var dtSt = $(this).html().split(" ");
var dtAr = dtSt[0].split("/");
var when = new Date(dtAr[1] + "/" + dtAr[0] + "/" + dtAr[2] + " " + dtSt[1]);
console.log(when);
var now = Date.now();
if (now - when > 3600000) {
$(this).addClass('min60');
} else if (now - when > 1800000) {
$(this).addClass('min30');
} else if (now - when > 1000) {
$(this).addClass('min1');
}
});
</script>
call "Highlighting code" inside ajax callback function if you are loading the same content again. My assumption is that the highlight part is getting replaced the ajax content.
.....
complete: function (xData, Status) {
var DVWPMarkup = $(xData.responseText).find("#reload_me").html();
$("#reload_me").html(DVWPMarkup);
hightlightcode(); //make sure to change the highlight code to a function
}
function highlightcode()
{
$('.IM_last_modified').each(function () {
var dtSt = $(this).html().split(" ");
var dtAr = dtSt[0].split("/");
var when = new Date(dtAr[1] + "/" + dtAr[0] + "/" + dtAr[2] + " " + dtSt[1]);
.....
}
It looks to me as if your highlighting code only runs once. You need to put the highlighting code in a function and call it every time there is new data to be highlighted.
Here is the script that finally worked for me, thanks everyone for the quick help.
<script type="text/javascript">
function reload() {
$.ajax({
async: false,
cache:false,
url: "http://ensemble-mtl.ent.cginet/sites/SERVIPCManagement/imc/Shared%20Documents/Whiteboard/Whiteboard.aspx",
complete: function (xData, Status) {
var DVWPMarkup = $(xData.responseText).find("#reload_me").html();
$("#reload_me").html(DVWPMarkup);
highlightcode_IM();
}
});
}
function highlightcode_IM()
{
$('.IM_last_modified').each(function () {
var dtSt = $(this).html().split(" ");
var dtAr = dtSt[0].split("/");
var when = new Date(dtAr[1] + "/" + dtAr[0] + "/" + dtAr[2] + " " + dtSt[1]);
console.log(when);
var now = Date.now();
if (now - when > 3600000) {
$(this).addClass('min60');
} else if (now - when > 1800000) {
$(this).addClass('min30');
} else if (now - when > 1000) {
$(this).addClass('min1');
}
});
}
$(document).ready(function(){
reload();
var auto_refresh = setInterval(function(){reload();}, 6000);
});
</script>
Something in my code is not working. I am new to this. I think it is the onload maybe?
I am trying to convert a 24 clock to a 12 hour GMT server time clock and I have got as far as passing my new code to the CSS div I made.
All the CSS is fine and my coding works well with alert but not with onload and document.getElementById.
<script>
var currenttime = '<? print date("F d, Y H:i:s a", time())?>'
var serverdate=new Date(currenttime)
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = serverdate.getHours();
var hours = ((hours24 + 11) % 12) + 2;
formatted = [formatted, [addZero(hours), addZero(serverdate.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");
}
document.getElementById("servertime").innerHTML=formatted
return formatted;
}
})();
window.onload=function(){
formatTime(new Date())
}
</script>
</head>
<body>
<h1><p><span id="servertime"></span></p></h1>
</body>
You could just write this, no need for javascript at all.
<h1><p><span id="servertime"><? print date("F d, Y h:i:s a", time())?></span></p></h1>
In case you are preparing a periodic update with your javascript (here it makes sense), I suggest using a simple jquery script for it:
$(document).ready(function() {
function update() {
$.ajax({
type: 'POST',
url: 'servertime.php',
timeout: 1000,
success: function(data) {
$("#servertime").html(data);
window.setTimeout(update, 1000);
},
});
}
update();
});