Change countdown when refresh the page? - javascript

I have my own webshop and on the home page i have a lot of products with countdown.
So whats the problem?
The problem is, when i have many javascripts on home page then the broser will freezing, getting slow.
How i know this is an javascript problem ? I tried to disable javascript on the browser and my website works normal.
/*!
*
* Brian2000: BK_Countdown v1.1
* AKA: Brian's jQuery Robust Date/Time Countdown
* http://brian2000.com
*
* Copyright 2012-2013, Brian Kennedy
* Licensed under the GPL Version 3 license
* http://www.gnu.org/licenses/gpl-3.0.en.html
*
* Date: Wed Jan 9 2013 2:54PM EST
*
* You can't remove this part, and if you make changes or improve things, please keep me informed.
* Thank you, enjoy, and support Open Source!
*/
/*
This portion explains how to use the counter, I recomend not deleting it either ;-)
VARS [required]
------------------------------------------------
container: ID of Element for counter
targetDate: MM/DD/YYYY
targetTime: HH:MM:SS (0-23 Hour) [seconds are optional]
OPTIONS:
------------------------------------------------
order: format/output order
order: 1 = Label + Spacer + Value
order: 2 = Value + Spacer + Label (reverse from order 1)
spacer: text/string seperator between label and value
element: html element for label and value containers (default is span)
end: Message to display when date has passed
dayOf: Message to display on day of counter expiration
*/
function BK_CountDown(container, targetDate, targetTime, opts) {
/////////////////////////////////////////////////////
//vars
this.opts = opts;
this.complete = false; //for exiting interval
this.container = container; //target
DArray = targetDate.split('/');
this.targetDate = DArray[0] + '/' + DArray[1] + '/' + DArray[2];
TArray = targetTime.split(':');
this.targetHour = TArray[0]; //hr
this.targetMin = TArray[1]; //min
if (typeof TArray[2] == 'undefined') { //sec
this.targetSec = 0;
}else{
this.targetSec = TArray[2];
}
/////////////////////////////////////////////////////
// options
var defaults = {
'order' : "1",
'spacer' : ':',
'element' : 'span',
'end' : "Deal is ended!",
'dayOf' : "Deal is ended!"
}
if(typeof this.opts != "undefined") { //if options were assigned...
for(var i in defaults) { //assign defaults for unchanged opts
if(typeof this.opts[i] == "undefined") {
this.opts[i] = defaults[i];
}
}
}else{ //no options were assigned
this.opts = defaults;
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// assembly
/////////////////////////////////////////////////////
s = this.opts['spacer'];
this.c = container.substring(1);
e = this.opts['element'];
if(this.opts['order'] == 2){
//reverse assembly
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">' + s + ' Days</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">' + s + ' :</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">' + s + ' :</' + e + '>');
}
else{
//default assembly
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">Days ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">Hours ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">Minutes ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// Count Update function
this.count_update = function count_update(){
date = new Date(); //NOW
targetDate = new Date(this.targetDate);
targetDate.setHours(this.targetHour);
targetDate.setMinutes(this.targetMin);
targetDate.setSeconds(this.targetSec);
var UDate = Math.round(date.getTime()/1000);
var UTargetDate = Math.round(targetDate.getTime()/1000);
differance = UTargetDate - UDate;
days=Math.floor(differance/(60*60*24)*1);
hours=Math.floor((differance%(60*60*24))/(60*60)*1);
minutes=Math.floor(((differance%(60*60*24))%(60*60))/(60)*1);
seconds=Math.floor((((differance%(60*60*24))%(60*60))%(60))*1);
//if range is 0 don't display range
//days
if(days <= 0){$(this.container + '_count_days').remove();$(this.container + '_txt_days').remove();}
else{$(this.container + '_count_days').text(days);}
//hours
if(days <= 0 && hours <= 0){$(this.container + '_count_hours').remove();$(this.container + '_txt_hours').remove();}
else{$(this.container + '_count_hours').text(hours);}
//min
if(days <= 0 && hours <= 0 && minutes <= 0){$(this.container + '_count_min').remove();$(this.container + '_txt_min').remove();}
else{$(this.container + '_count_min').text(+minutes);}
//seconds
$(this.container + '_count_sec').text(seconds);
//Singular text for 'reverse' assembly
if(this.opts['order'] == 2){
if(days <= 1){$(this.container + '_txt_days').text(this.opts['spacer'] + ' dag en ');}
else{$(this.container + '_txt_days').text(this.opts['spacer'] + ' dagen en ')}
if(hours == 1){$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
else{$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
if(minutes == 1){$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
else{$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
if(seconds == 1){$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
else{$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
}
//end of countdown
if(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0){
//timer is over, final output
//if date is today!
if(new Date().toDateString() == targetDate.toDateString()){
$(this.container).addClass('count_now');
$(this.container).text(this.opts['dayOf']);
}else{//if date is after today
$(this.container).addClass('count_end');
$(this.container).text(this.opts['end']);
}
this.complete = true;
}
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//run immediately
this.count_update();
//now loop this every second
var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
}
HTML:
$(document).ready(function() {
var aanbiedingcountdown = new BK_CountDown('#deal1', '05/25/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal2', '05/26/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal3', '05/28/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal4', '05/28/2014', '15:10', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal5', '05/26/2014', '23:57', {order: 2, spacer: ''});
});
You see, for every countdown that i want i need to create an ID.
But what i want is that when the page load, the countdown dont need to run, it makes my website slower. So, only when the someone refresh the page then he get the right date & time.
Example: Time is now 16:00u, the countdown are set at 17h, so, when someone is still on my website (10min) without refreshing the page then the countdown is still 16h only if he refresh the page then countdown is 16:10h...
I've seen this on other websites and they have more than 100 products with countdowns on the same page and still works perfect because timer is not running only if people refresh the page the the timer will set to right date & time.
Demo: http://jsfiddle.net/uJk73/ (i removed seconds, i though site will go faster without this, but no succes)
Hope someone can help my with this.

Updated jsfiddle
So let's say you had 9 deals
<div id="countdowntimer">
<div id="deal1"></div>
<div id="deal2"></div>
<div id="deal3"></div>
<div id="deal4"></div>
<div id="deal5"></div>
<div id="deal6"></div>
<div id="deal7"></div>
<div id="deal8"></div>
<div id="deal9"></div>
</div>
Get rid of this loop in BK_CountDown()
//now loop this every second
/*var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
*/
Then
$(document).ready(function() {
var deals = []; // create an array
deals.push( new BK_CountDown('#deal1', '05/24/2014', '23:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal2', '05/24/2014', '22:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal3', '05/24/2014', '12:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal4', '05/24/2014', '13:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal5', '05/24/2014', '14:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal6', '05/24/2014', '15:57', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal7', '05/24/2014', '15:58', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal8', '05/24/2014', '15:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal9', '05/24/2014', '16:00', {order: 2, spacer: ''}) );
var dealcounter = setInterval(function(){ // create one setTimeout
if (deals.length){
for (i in deals){
var selfobject = deals[i];
selfobject.count_update();
if(selfobject.complete == true) delete deals[i]; // remove from array
}
}else{
clearTimeout(dealcounter); // no more to count down, stop this loop
}
}, 5000); // 5 seconds
});

Related

Script does not show original image

Guys I have a script that shows blogger articles, only the images of the articles are of poor quality.
Looking at the script the only part that refers to the image is this
// Get the post thumbnails
postimg = ("media$thumbnail" in entry) ? entry.media$thumbnail.url : imgBlank;
// Build the post template
output += '<div class="itemposts">';
output += '<h6>' + posttitle + '</h6>';
output += '<div class="iteminside"><img src="' + postimg + '" />';
output += '<span class="summary">' + postsumm + '</span></div>';
output += '<div style="clear:both;"></div><div class="itemfoot">' + timepub + replies + '<a class="itemrmore" href="' + posturl + '">' + rmoreText + '</a></div>';
output += '</div>';
css code:
.itemposts img {
float:left;
height:90px;
width:200px;
margin:2px 10px 2px 0px;
-webkit-box-shadow:none;
-moz-box-shadow:none;
box-shadow:none;
background-color:#fafafa;
border:1px solid #dcdcdc;
padding:4px;
}
Does anyone know which part of the code needs to be changed to show the image with the original quality?
added full code full code
<script>
var showPostDate = true,
showComments = true,
idMode = true,
sortByLabel = false,
labelSorter = "Games",
loadingText = "Loading...",
totalPostLabel = "Jumlah posting:",
jumpPageLabel = "Halaman",
commentsLabel = "Komentar",
rmoreText = "Selengkapnya ►",
prevText = "Sebelumnya",
nextText = "Berikutnya",
siteUrl = "https://elfenliedbrazil.blogspot.com/",
postPerPage = 6,
numChars = 370,
imgBlank = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC";
</script>
<script type='text/javascript'>
//<![CDATA[
// -----------------------------------------------------------------------------------------
//
// Original:
// Modified by Taufik Nurrohman
//
// -----------------------------------------------------------------------------------------
var minpage = 6; // Minimum number to display the page
var maxpage = 10; // The maximum number of pages to display
var firstpage = 0; // Detect the first time it is executed
var pagernum = 0; // Contain the page number where we
var postsnum = 0; // Start the first page
var actualpage = 1; // Starting value of the current page (it will change if you click the pagination).
// This is the container template that will be used to insert the posts template, pagination and the posts count
document.write('<div id="toc-outer"><div id="results"></div><div id="itempager" style="position:relative;"><div id="pagination"></div><div id="totalposts"></div><a title="Taufik Nurrohman" style="display:block!important;visibility:visible!important;opacity:1!important;position:absolute;bottom:10px;right:14px;font:normal bold 8px Arial,Sans-Serif!important;color:#666;text-shadow:0 1px 0 rgba(255,255,255,.1);text-decoration:none;" href="http://hompimpaalaihumgambreng.blogspot.com/2012/03/daftar-isi-blogger-dengan-navigasi.html" target="_blank">►TN</a></div></div>');
var _results = document.getElementById('results');
var _pagination = document.getElementById('pagination');
var _totalposts = document.getElementById('totalposts');
// Build the table of contents framework
function showPagePosts(json) {
var entry, posttitle, posturl, postimg, postsumm, replies, monthnames, timepub, output = "";
if (pagernum === 0) {
postsnum = parseInt(json.feed.openSearch$totalResults.$t);
pagernum = parseInt(postsnum / postPerPage) + 1;
}
for (var i = 0; i < postPerPage; i++) {
if ("entry" in json.feed) {
if (i == json.feed.entry.length) break;
entry = json.feed.entry[i];
posttitle = entry.title.$t; // Get the post title
// Get rel="alternate" for truly post url
for (var k = 0, elen = entry.link.length; k < elen; k++) {
if (entry.link[k].rel == "alternate") {
posturl = entry.link[k].href; // This is your real post URL!
break;
}
}
// Get the comments count
for (var l = 0, clen = entry.link.length; l < clen; l++) {
if (entry.link[l].rel == "replies" && entry.link[l].type == "text/html") {
var commentsnum = entry.link[l].title.split(" ")[0]; // This is your comments count
break;
}
}
// If the Blogger-feed is set to SHORT, then the content is in the summary-field
postsumm = ("summary" in entry) ? entry.summary.$t.replace(/<br ?\/?>/ig, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : ""; // Get the post summary
// Reduce post summaries to "numChars" characters.
// "numChars" is a variable. You determine the value
if (postsumm.length > numChars) {
postsumm = (numChars > 0 && numChars !== false) ? postsumm.substring(0, numChars) + '...' : "";
}
// Get the post date (e.g: 2012-02-07T12:56:00.000+07:00)
var _postdate = entry.published.$t,
_cdyear = _postdate.substring(0, 4), // Take 4 characters from the "postdate" beginning, it means the year (2012)
_cdmonth = _postdate.substring(5, 7), // Take 2 character 5 step from "postdate" beginning, it mean the month (02)
_cdday = _postdate.substring(8, 10); // Take 2 character 8 step from "postdate" beginning. it means the day (07)
// Month array template
monthnames = (idMode) ? ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agt", "Sep", "Okt", "Nov", "Des"] : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// The final product of the post date = (07 Feb 2012) (cdday monthnames cdyear)
timepub = (showPostDate) ? _cdday + ' ' + monthnames[parseInt(_cdmonth, 10) - 1] + ' ' + _cdyear + ' - ' : '';
// The final product of the comments count & comments label (10 Komentar) (commentsnum commentsLabel)
replies = (showComments) ? commentsnum + ' ' + commentsLabel : '';
// Get the post thumbnails
postimg = ("media$thumbnail" in entry) ? entry.media$thumbnail.url : imgBlank;
// Build the post template
output += '<div class="itemposts">';
output += '<h6>' + posttitle + '</h6>';
output += '<div class="iteminside"><img src="' + postimg + '" />';
output += '<span class="summary">' + postsumm + '</span></div>';
output += '<div style="clear:both;"></div><div class="itemfoot">' + timepub + replies + '<a class="itemrmore" href="' + posturl + '">' + rmoreText + '</a></div>';
output += '</div>';
}
}
// Put the whole template above into <div id="results"></div>
_results.innerHTML = output;
_create_pagination();
}
// Build the pagination
function _create_pagination() {
output = "";
var starter = 0;
output += ((actualpage > 1) ? '<a title="' + prevText + '" class="prevjson" href="javascript:_init_script(' + (actualpage - 1) + ')">' + prevText + '</a>' : '<span class="prevjson hidden">' + prevText + '</span>') + '<em style="font:inherit;color:inherit;" class="pagernumber">';
if (pagernum < (maxpage + 1)) {
for (starter = 1; starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
} else if (pagernum > (maxpage - 1)) {
if (actualpage < minpage) {
for (starter = 1; starter < (maxpage - 2); starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else if (pagernum - (minpage - 1) > actualpage && actualpage > (minpage - 1)) {
output += '1';
output += '2';
output += ' ... ';
for (starter = actualpage - 2; starter <= actualpage + 2; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else {
output += '1';
output += '2';
output += ' ... ';
for (starter = pagernum - (minpage + 1); starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
}
}
output += '</em>' + ((actualpage < starter - 1) ? '<a title="' + nextText + '" class="nextjson" href="javascript:_init_script(' + (actualpage + 1) + ')">' + nextText + '</a>' : '<span class="nextjson hidden">' + nextText + '</span>');
_pagination.innerHTML = output;
_totalposts.innerHTML = totalPostLabel + ' ' + postsnum + ' - ' + jumpPageLabel + ' ' + ((actualpage * postPerPage) - (postPerPage - 1)) + ((actualpage < starter - 1) ? ' - ' + (actualpage * postPerPage) : "");
}
// Functions to remove and append the callback script that has been manipulated in the `start-index` parameter
function _init_script(n) {
var parameter = (n * postPerPage) - (postPerPage - 1), old, s,
head = document.getElementsByTagName('head')[0],
url = (sortByLabel) ? siteUrl + '/feeds/posts/summary/-/' + labelSorter + '?start-index=' + parameter : siteUrl + '/feeds/posts/summary?start-index=' + parameter; // Optional: Sort posts by a specific label
if (firstpage == 1) {
// Jump to top
document.documentElement.scrollTop = _results.offsetTop - 30;
document.body.scrollTop = _results.offsetTop - 30;
// Remove the old callback script
old = document.getElementById("TEMPORAL");
old.parentNode.removeChild(old);
}
_results.innerHTML = '<div id="loadingscript">' + loadingText + '</div>';
_pagination.innerHTML = '';
_totalposts.innerHTML = '';
s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&max-results=' + postPerPage + '&orderby=published&alt=json-in-script&callback=showPagePosts';
s.id = 'TEMPORAL';
head.appendChild(s);
firstpage = 1;
actualpage = n;
}
// Execute the _init_script() function with parameter as `1` on page load
// So it will show the first page.
window.onload = function() {
_init_script(1);
};
//]]>
</script>
Thumbnails are reduced-size versions of pictures or videos
https://en.wikipedia.org/wiki/Thumbnail
So you need to get the original image
In some cases you have the size in the url, like in this one at the end of url
https://lh3.googleusercontent.com/mC69w8Asl2c4y8it_gEb0-2CcwxKWUvz1fs4gOwVfxUkvSN7qAAl41VohsqSdVG-dZs=w720-h110-rw
You can simply remove that part and get the full size of the image
https://lh3.googleusercontent.com/mC69w8Asl2c4y8it_gEb0-2CcwxKWUvz1fs4gOwVfxUkvSN7qAAl41VohsqSdVG-dZs
update
In your case you have a url like this
https://1.bp.blogspot.com/xxxxxxx/s72-c/xxxxx.jpg
you can change to
https://1.bp.blogspot.com/xxxxxxx/s640/xxxxx.jpg
This post explain very well how you can use List of all the App Engine images service get_serving_url() URI options

Google Api Calendar If else ,done with javascript

So I'm doing Google Calendar Api, that shows all the booked things for that day. I'm trying to get this code to print 'Vapaa' (means free in finnish and is shown if there's nothing booked in that time) only once but still print the rest of the appointments that come later that day. Here's the code that does the if else
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = new Date(event.start.dateTime);
var hs = addZero(when.getHours());
var ms = addZero (when.getMinutes());
var end = new Date(event.end.dateTime);
var he = addZero(end.getHours());
var me = addZero (end.getMinutes());
var now = new Date();
var hn = addZero(now.getHours());
var mn = addZero (end.getMinutes());
if (!when) {
when = event.start.date;
}
if (when.getTime() <= now.getTime() && now.getTime() <= end.getTime()){
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
} else {
appendPre('Vapaa');
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
}
return;
}
} else {
appendPre('Ei varauksia');
}
Also the appendPre is printed to html with this code
function appendPre(message) {
if (message != 'Vapaa'){
var pre = document.getElementById('booked');
var textContent = document.createTextNode(message + '\n' + '\n');
} else {
var pre = document.getElementById('free');
var textContent = document.createTextNode(message + '\n' + '\n');
}
pre.appendChild(textContent);
}
I'm so lost so any help would be awesome.
return; stops right where it is and exits the function, so your for loop will only run once with the return in there. See W3C for more info.
Typically, if you want to exit only the loop, but continue in the function (if you have code after it, it doesn't look like you've shown that here), you can use break;. If you want to skip the rest of the stuff in the for loop (nothing is shown in your example), but continue iterating onto the next entry, you can use continue;. See W3C for more details.

SQL node.js Syntax error on what seems to be a valid query?

I'm running an update on a table to set a position. I've extracted the query and manually run it on my database and works fine but when passed through connection.query() it seems to think there's a syntax error in my node.js console.
function sendShipPosition(position) {
var input = '';
if (position.moving === true) {
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
var input = ', moving_datetime = ' + datetime;
}
connection.query('UPDATE ships SET x_axis = :x, y_axis = :y' + input + ' WHERE ship_id = :ship_id'), {
x: parseInt(position.x),
y: parseInt(position.y),
ship_id: 1
};
}
Here is the syntax error:
Here's the input data value of 'position' variable:
{ x: '-605', y: '-257', moving: 0 }
I hope I'm not being too much of a dunce and sorry for the low quality question.
Thanks
This function will generate SQL code which is missing quotes around the datetime variable, resulting in invalid SQL code.
function sendShipPosition(position) {
var input = '';
if (position.moving === true) {
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
# Here!
var input = ', moving_datetime = \'' + datetime + '\''
}
connection.query('UPDATE ships SET x_axis = :x, y_axis = :y' + input + ' WHERE ship_id = :ship_id'), {
x: parseInt(position.x),
y: parseInt(position.y),
ship_id: 1
};
}

Render a RealTime Clock after append in Jquery

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.

Javascript - How do I capture and respond to a post?

I am developing an application to respond to a punch out, but am missing something. I can create the reponse XML document fine, but the receiving end is not seeing my response. I have found hundreds of examples on the web about the post process, but cannot seem to figure out what the server is supposed to do to reply to the post. If anyone can offer an example of the server side of this, that would be greatly appreciated.
Update
Here is the code that I have. I did replace the SEND with a display to see what it was I am trying to send. I am very new to this, so any insight would be helpful.
<script language="javascript">
var xmlhttp;
var xmlrtn;
<!-- Begin
Stamp = new Date();
year = Stamp.getYear();
month = Stamp.getMonth() + 1;
if (month < 10) {month = "0" + month;}
ddate = Stamp.getDate();
if (ddate < 10) {ddate = "0" + ddate;}
if (year < 2000) year = 1900 + year;
//document.write(year + "-" + month + "-" + ddate);
timestamp = year + "-" + month + "-" + ddate;
var Hours;
var Mins;
var Time;
Hours = Stamp.getHours();
Mins = Stamp.getMinutes();
if (Mins < 10) {
Mins = "0" + Mins;
}
Secs = Stamp.getSeconds();
if (Secs < 10) {Secs = "0" + Secs;}
//document.write('T' + Hours + ":" + Mins + ":" + Secs);
timestamp = timestamp + 'T' + Hours + ":" + Mins + ":" + Secs;
// End -->
xmlhttp=new ActiveXObject("Microsoft.XMLDOM");
var o="<";
var c="/" + ">";
var tc="<" + "/";
var e=">";
var params=new Array();
var xmlrtn = '';
function loadXML(xmlFile)
{
xmlhttp.async="false";
xmlhttp.onreadystatechange=verify;
xmlhttp.load(xmlFile);
xmlObj=xmlhttp.documentElement;
}
function verify()
{
// 0 Object is not initialized
// 1 Loading object is loading data
// 2 Loaded object has loaded data
// 3 Data from object can be worked with
// 4 Object completely initialized
if (xmlhttp.readyState != 4)
{
return false;
}
}
</script>
</head>
<body>
<script language="javascript">
//Read in XML file
loadXML('https://www.americantexchem.com:9443/storefrontContent/attach/sample.xml');
//Assign Variables
var xmlver='?xml version="1.0"?';
var doctype='!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.1.007/cXML.dtd"';
xmlLang=xmlObj.getAttribute("xml:lang");
var cxmltag=xmlObj.tagName;
var cxmlval=' version="' + xmlObj.getAttribute("version") + '" payloadID="' + xmlObj.getAttribute("payloadID") + '" timestamp="' + timestamp + '"';
var resptag='Response';
var statustag='Status code="200" text="success" ';
var poutsrtag='PunchOutSetupResponse';
var startpgtag='StartPage';
var urltag='URL';
var urlval='https://www.americantexchem.com:9443/storefrontCommerce/jsp/wynlogin.jsp';
var srcurlval = xmlObj.childNodes(1).childNodes(0).childNodes(2).childNodes(0).firstChild.text; //URL content
// post
params[0] = o + xmlver + e;
params[1] = o + doctype + e;
params[2] = o + cxmltag;
params[3] = cxmlval + e;
params[4] = o + resptag + e;
params[5] = o + statustag + c;
params[6] = o + poutsrtag + e;
params[7] = o + startpgtag + e;
params[8] = o + urltag + e;
params[9] = urlval;
params[10] = tc + urltag + e;
params[11] = tc + startpgtag + e;
params[12] = tc + poutsrtag + e;
params[13] = tc + resptag + e;
params[14] = tc + cxmltag + e;
for (var i in params) {
if (params.hasOwnProperty(i)) {
// var input = document.createElement('input');
// input.type = 'hidden';
// input.name = i;
//input.value = params[i];
// form.appendChild(input);
xmlrtn = xmlrtn + params[i];
}
}
// alert (xmlObj.xml);
document.write (xmlrtn);
/*
var fso = new ActiveXObject("Scripting.FileSystemObject");
fileBool = fso.FileExists("C:\\out.xml");
if(fileBool)
{
//document.write("Test-fileBool");
fso.DeleteFile("C:\\out.xml",true);
}
var fso, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
s = fso.OpenTextFile("C:\\out.xml" , 8, true);
s.writeline (o + xmlver + e);
s.writeline (o + doctype + e);
s.writeline (o + cxmltag);
s.writeline (cxmlval + e);
s.writeline (o + resptag + e);
s.writeline (o + statustag + c);
s.writeline (o + poutsrtag + e);
s.writeline (o + startpgtag + e);
s.writeline (o + urltag + e);
s.writeline (urlval);
s.writeline (tc + urltag + e);
s.writeline (tc + startpgtag + e);
s.writeline (tc + poutsrtag + e);
s.writeline (tc + resptag + e);
s.writeline (tc + cxmltag + e);
// s.writeline (xmlObj.xml); // the whole source xml document
s.Close();
*/
</script>
</body>
</html>
This will depend a bit on your server side technology. Here is an example post using asp.net mvc.
http://blog.bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/
Hope this helps getting you started
Bob

Categories