Function in javascript won't update directly, have to refresh page - javascript

In my javascript
$(document).ready(function() {
console.log((new Date().getTime() / 1000));
if ((new Date(setting.lastDate).getTime() / 1000) <= (new Date().getTime() / 1000)) {
$('.Go').removeAttr("disabled");
$( ".headertesting").replaceWith(" ");
$( ".testing" ).replaceWith( "<span class='butlabel testing' >Register Now!</span><span class='spinner'></span>" );
}
});
In my html when i run this function . It's not worked as i expected
I have a countdown date:
Example i set
lastDate = "06/01/2016 10:21:00"
So it will check my currentTime and compare it. But when it reach. the button didn't update directly. I have to refresh the page only see the result. What i want is directly button change without refresh page once time reached.

That's because $(document).ready() executes only once, when the page loads. You're probably expecting that your function executes repeatedly, maybe every second or so, so that it updates as soon as the timer reaches that condition. Try window.setTimeout or window.setInterval. Here's a related question with a good answer: What's the easiest way to call a function every 5 seconds in jQuery?.

When you say "is not working", what did you try?
var resultsEl = document.getElementById("time");
window.setInterval(function(){
resultsEl.innerText = new Date().toLocaleTimeString();
}, 1000);
<div id="time" style="height: 1em; background-color: aliceblue;"></div>

Related

I'm having problem on auto refreshing a content in a web page

I'm creating a webpage that will automatically refresh a content to always get the latest data in the database. This is my code in Javascript.
setInterval(function() {
$("#status").load('refresh.php');
},1000);
In my javascript, I'm automatically refreshing the #status with refresh.php every second.
But when I inspect the element of my webpage and click on the network. It is also requesting(spamming) the refresh.php every second which is I think a bad practice.
Can you help me how to fixed this? Or can you suggest better ajax code to auto refresh a content without requesting the php file too much?
You should probably use a websocket for this, get the latest status as data from the server and then change only that section of the page using javascript
This code will be request refresh.php later at timeouts.min every time when new (requested) value of #status is equal to current. If values are different, next timeout will be timeouts.min again.
var timeouts={
min:1000, // min await timeout = 1s
max:16000 // max await timeout = 16s
};
var currentTo = timeouts.min;
function setAutoRefresh( to ){
setTimeout( function() {
var current = $("#status").text();// or .html()
$("#status").load('refresh.php', function() {
// if we are load a new value
if( current !== $("#status").text()) {
currentTo = timeouts.min;
// if loaded value are same to current
} else {
currentTo += timeouts.min; // or currentTo *= 2; for example
if( currentTo > timeouts.max ){
currentTo = timeouts.max;
}
}
console.log('Next #status refresh after ' + currentTo + 'ms');
// Set a new timeout
setAutoRefresh( currentTo );
});
}, to);
}
// Set the first timeout
setAutoRefresh( timeouts.min );

disable button with PHP and JavaScript when time is gone

I try to disable Apply button when application deadline is over. I used php and I successfully got time on each button. Now different time is print on different button.
<td><input type='submit' value='Apply' id='button' name='button' date-time='$closedate' /></td>
I used jquery/ javascript to disable button after expired time (after deadline of application), it cannot disable and it always enable.
In the code below code I used for disable button but it not works.
<script>
$(document).ready(function() {
var timer = setInterval(function() {
var current = $("#button").data('time');
// get the current value of the time in seconds
var newtime = current - 1;
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$("#button").prop('disabled', true);
clearInterval(timer);
} else {
// timer is still above 0 seconds so decrease it
$("#button").data('time', newtime);
}
}, 1000);
});
</script>
based on what you have put down, it seems there are a few simple errors that need to be looked at
1) looks like a simple typo -- date-time should be data-time
2) you are not actually outputting the value of $closedate try changing it to
without knowing what the value of $closedate is, we won't be able to help further than that
Here is a fiddle that replicates an example...https://jsfiddle.net/o2gxgz9r/6656/
Your main issue is that you are mispelling the data-time attribute in your code as date-time. Your html should be as follows...
<input type='submit' value='Apply' id='button' name='button' data-time='$closedate' />
After fixing that, you should be able to reference the data value. Moreover, you are not updating the data value, so every time setInterval is called, the variable $closedate remains the same, and so the if statement if (newtime <= 0) is never reached...
var timer = setInterval(function() {
// get the current value of the time in seconds
var current = $("#button").data('time');
// decrement the time
var newtime = current - 1;
// update $closedate
$("#button").data('time', newtime);
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$("#button").prop('disabled', true);
clearInterval(timer);
} else {
// timer is still above 0 seconds so decrease it
$("#button").data('time', newtime);
}
}, 1000);
I am not sure what the value of $closedate is but I made an assumption in my fiddle.
A few of issues...
First, in your HTML, you have date-time instead of data-time, so when you go to get the attribute later with: $("#button").data('time'), you won't get anything.
Second, you must remember to convert HTML data (which is always a string) to numbers to do math with them.
Third, you need to verify that $closedate is a string that can be converted into a valid number. You indicated in a comment below that $closedate will be something like: 2017-03-17. But that is not a value that you can subtract from.
Lastly, updating the HTML is costly in terms of performance. You are modifying the data-time attribute upon each iteration of your setInterval(), which is roughly every second. This can and should be avoided. It can be done by keeping the time left in a variable instead of writing it back to the document.
Here's a working version:
$(document).ready(function() {
// Always cache references to elements you will use more than once:
var $btn = $("#button");
// When gettting data from HTML, you get strings. You must convert
// them to numbers to do math with them. Also, we are using 5 seconds
// here instead of $closedate for testing purposes.
var current = parseInt($btn.data('time'), 10);
// Initialize the newtime for comparison
var newtime = current;
var timer = setInterval(function() {
newtime--; // Decrease the time left
// Just testing the variables:
console.log(current, newtime);
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$btn.prop('disabled', true);
clearInterval(timer);
}
current--; // Decrease the counter
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='submit' value='Apply' id='button' name='button' data-time='5'>

function not working properly when run on document ready

I have a form with 2 fields: date field #datefromtoday and number of days #daysfromtoday. I use a javascript function to:
1) Automatically listen to the datefromtoday and (if there is a date) display the number of days from today when the page is loaded
2) adjust the date from today when entering/modify the number of days.
Here is the code:
$(document).ready(function (){
function modifyDays(){ //definy function to modify days
var endDateToDays = $( "#datefromtoday" ).val();
var endDateToDays_obj = new Date(endDateToDays); // convert in object
var endDateToDays_ms = endDateToDays_obj.getTime(); // convert in ms
var todayDate = new Date(); //
var todayDate_ms = todayDate.getTime(); //
var daysFromToday = parseInt(Math.ceil( (endDateToDays_ms - todayDate_ms) / 1000 / 60 / 60 / 24 ) ) || ''; //if not number display nothing
document.getElementById("daysfromtoday").value = daysFromToday; //outuput
}
modifyDays(); //here is the problem. If I delete this line of code, everything works perfectly
$("#datefromtoday").on('change', function(){ //run function when modify delay date
modifyDays();
});
});
PROBLEM
the modifyDays function works like a charm on the on.change event, but
when is loaded on document ready, it interferes with datatables www.datatables.net and also with other scripts, and they don't work anymore...
I'm probably using the wrong code to call the function on page load.... any ideas? Thanks for your help!!!
If you think it is because of calling the main function, in the body element of the html page, add an onload attribute:
<body onload="loaded()">
and declare loaded as that main function:
var loaded = function (){
function modifyDays(){ //definy function to modify days
var endDateToDays = $( "#datefromtoday" ).val();
var endDateToDays_obj = new Date(endDateToDays); // convert in object
var endDateToDays_ms = endDateToDays_obj.getTime(); // convert in ms
var todayDate = new Date(); //
var todayDate_ms = todayDate.getTime(); //
var daysFromToday = parseInt(Math.ceil( (endDateToDays_ms - todayDate_ms) / 1000 / 60 / 60 / 24 ) ) || ''; //if not number display nothing
document.getElementById("daysfromtoday").value = daysFromToday; //outuput
}
modifyDays(); //here is the problem. If I delete this line of code, everything works perfectly
$("#datefromtoday").on('change', function(){ //run function when modify delay date
modifyDays();
});
};
Then it should work if the problem is how the function is called.
I don't think the problem is because of you are calling the function on page load. The error might be coming from inside the function modifyDays. Only dependency I see is #datefromtoday and #daysfromtoday. Check whether those nodes are there when the function execute on dom ready event.
If the timing of the function call is the problem, you can put the modifyDays(); call in a window.setTimeout(modifyDays, 5000); or something of the sort to delay it until the other scripts finish loading, so this snippet doesn't interrupt or interfere with them. You may want to put a placeholder in the html for the seconds when it isn't loaded yet if this works.

Auto refresh a page with count down time

I have a small C# code behind to refresh a webform page (form.aspx) after 15 seconds as below:
lblMessage.Text = "<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after 15 seconds)";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setInterval(function(){location.href='/form.aspx';},15000);", true);
Right now the page will be refreshed after 15 seconds. How do I also make the timer count down every second? i.e., 15 => 14 => 13 => ... 1 then refresh so it will be better for users, they will know what is going on with the page...
In javascript I would go with something like this.
<div id='countdown'></div.
var countDown = 15;
function countdown() {
setInterval(function () {
if (countDown == 0) {
return;
}
countDown--;
document.getElementById('countdown').innerHTML = countDown;
return countDown;
}, 1000);
}
countdown();
Fiddle: http://jsfiddle.net/chzzcosy/
"<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after <span id='counter'>15</span> seconds)"
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setTimeout(function(){location.href='/form.aspx';},15000); counter = 15; setInterval(function(){counter--; document.getElementById('counter').innerHTML = counter;},1000);", true);
Should do it.
If added a span with id counter around the refresh message number.
Then I added counter = 15; to initialize a default value of 15. And another setInterval to the script block firing every second. With each pass it subtracts one from counter and updates the span with the new counter value. Users should now see the page counting down. I also changed the first setInterval to setTimout, since it's technically a timeout and not an interval that should occur every 15 seconds.

Monitor single page loading times in javascript

I've got an existing single page web application of which I can't change the code. Some users complain that the application is not performing very well.
I would like to monitor the loading time in this way:
Record the time stamp of a click on the page
Record the time stamp of when the rendering of the page has been completed, after ajax requests and some other javascript magic has been done
Calculate the difference between the two time stamps and post it back to the server.
I can easily do step 1 and 3 with jQuery, however I'm not sure what's the best way to approach step 2?
As this seems to be a quite obvious scenario, is there a standard tool set to perform this kind of monitoring?
This helps:
function onLoad() {
var now = new Date().getTime();
var page_load_time = now - performance.timing.navigationStart;
console.log("User-perceived page loading time: " + page_load_time);
}
You could use the global ajaxStop event jQuery offers.
var start = +(new Date());
$(document).ajaxStop(function() {
var diff = +(new Date()) - start;
// do logging
});
This won't include the code executed after the last AJAX call, but if things happening before the last call contain the expected bottleneck, then this will be quite useful.
this can be achieved in following way...
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
var startTime, endTime, timeDifference;
function doIt() {
var startTime = new Date().getTime();
$.ajax({
type: 'post',
url: 'a.php',
success: function (resp) {
endTime = new Date().getTime();
timeDifference = endTime - startTime; //Time Difference is stored in milliseconds
}
})
}
</script>
</head>
<body>
<button style="position: absolute; top:60px" onclick="doIt()">start</button>
</body>
</html>
It's not a perfect solution, however the following code is working. It start the timer when a user clicks. The checkHTML function monitors the changes in the page content.
var timeLogging = new Array();
var timeStart;
$(document).click(function() {
initLogEvent();
});
function initLogEvent() {
caption = $(".v-captiontext:first").text();
timeStart = +(new Date());
timeLogging.push(new Array(0,0));
timeLogging[timeLogging.length - 1][0] = timeStart;
}
initLogEvent();
// Start a timer to check the changes in html
window.setInterval(checkHtml, 250);
// Start a timer to create the reports
window.setInterval(sendReport, 1000);
var html;
function checkHtml() {
current = $("body").html();
if (current != html) {
html = current;
var diff = +(new Date()) - timeStart;
timeLogging[timeLogging.length - 1][1] = diff;
}
}
function sendReport() {
if (timeLogging.length > 3) {
console.log(timeLogging);
// Do additional stuff with the collected data
for (i = 0; i <= timeLogging.length; i++) {
timeLogging.shift();
}
}
}
Are you keeping all you application's markup in the page, even when it is hidden? If so you are probably choking the browser's memory. I recommend learning to offload your markup in localStorage like Bing and Google pioneers a few years ago. I wrote a blog about it the day I discovered the technique and I have used it ever since.
http://love2dev.com/#!article/Use-Local-Storage-to-Make-Your-Single-Page-Web-Application-Rock

Categories

Resources