Javascript Refresh - javascript

Is there a way using the code below to instead of refreshing the time refresh a div id that is already there?
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('drawaddrow').innerHTML = ????;
}
</script>
Say I fi were to replace the time id with the the id that I wanted to refresh what would I put after .innerHTML =???
This is the div I need refreshed every second.
<div id="draw" align="center">
<table>
<tr><td style="height:20px;"></td></tr>
</table>
<TABLE style="float:center;border:5px; border-style:outset;border-color:#E80000; width:850px; border-spacing:0; border-collapes:collapse;" table border="1">
<div id="addrow"><script type="text/javascript">
Draw ("")
[Add]</script></div>
</table>
</div>
The [AddItemsHTML] somehow pulls data from a piece of software telling you what is due and what is not, however the script is not pulling the time every second the browser when refreshed just changed the time on the due status column.
Right now i'm using this to refresh the whole page I just need the drawaddrow div id refreshed.
function refreshPage () {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function () {
setTimeout(refreshPage, 1000);
if (window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
document.getElementsByTagName("body")[0].scrollTop = match[1];
}

Updated (on 27/07/2013 #08:20 AM IST):
Having gone through your code, the below is my updated answer.
Plainly assigning a value to the DIV (divaddrow) using (.innerHTML) wouldn't work due to the following reasons:
(a) The DIV has some code enclosed within square braces (like [AddItemsHTML]). I am not sure what technology it uses. But judging by its intended use (which is, to populate the table with data) it sure seems to require a communication with the server to fetch data.
(b) The DIV also has a <script> tag with a call to a function (lets call it cntFn). Plainly assigning the value would not work because value setting wouldn't call/execute the function again (like it does on page load).
Assuming point 1.a is wrong, the normal way to handle 1.b would be to first assign the static contents of the div using .innerHTML and then do either (a) write whatever the "cntFn" does into the function that is refreshing the page (lets call it refreshFn) also (or) (b) call the "cntFn" within the "refreshFn". The latter would also cause a problem here because the "cntFn" has a lot of document.write lines which would repaint the entire page (meaning the other contents of the page would be lost on executing the refresh).
Generally using document.write lines is a bad practice because they repaint the page fully. You can find more about this here.
The best alternate in my opinion would be to use AJAX to refresh the contents. The content of your divaddrow div would form the contents of the AJAX file that needs to be called every 'x' seconds. Be careful with the 'x' seconds part. Do not try to refresh the section every second because realistically it would take time for the AJAX request to reach the server and get the response. Set the refresh interval such that the first request would have been processed by the time the next one comes (at-least 90% of the cases). The amount of data (no. of rows) that the AJAX call would be fetching will also be a factor.

Check this out... I used Jquery for the same
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$('#show').text(
'I am getting refreshed every 3 seconds..! Random Number ==> '
+ randomnumber);
}, 3000);
});
WORKING FIDDLE

I'm not sure that I understand you, but is this want you mean?
function startTime()
{
document.getElementById('time').innerHTML = document.getElementById('target').innerHTML;
}

This is what I use:
<span>This page will refresh in </span><span id="countdown">60</span>seconds…
<script type="text/javascript">
setInterval(
function() {
if (document.getElementById('countdown').innerHTML != 0) {
document.getElementById('countdown').innerHTML--;
} else {
window.location = window.location;
}
}, 1000);</script>

If I've understood your question correctly, you can do something like this:
window.onload = function () {
function startTime () {
document.getElementById('date').innerHTML = new Date();
}
setInterval(startTime, 1000);
}
HTML:
<div id="time">This a div containing time: <span id="date"></span></div>

This is a JavaScript snippet, based on the original post, that counts the number of seconds since the page has loaded, assuming that there's an element with ID "time" and contents that are entirely numeric.
If the time remaining is given in seconds on the page you're working with, then it would be easy to adjust this accordingly. If the time remaining is not given in seconds, I'd need to see what the text in question actually looks like.
window.onload = startInterval;
var firstTime;
var valAtPageLoad;
function startInterval()
{
firstTime = new Date();
valAtPageLoad = parseInt(document.getElementById('time').innerHTML);
setInterval("startTime();",1000);
}
function startTime()
{
var timeDiff = (new Date() - firstTime)/1000;
document.getElementById('time').innerHTML = Math.round(timeDiff + valAtPageLoad);
}

If you want to reload your DIV and not the entire page, you would have to create the contents of that DIV on the server-side, and then use AJAX to load the DIV´s content. The easiest way to do this, is with jQuery:
function startTime() {
$.get('path/to/div/contents.html', function(data) {
$('#drawaddrow').html(data);
});
}

Related

How to carry on a function from one HTML page to another?

function display() {
document.querySelector(".recipeList").innerHTML = "";
for (var i = 0; i < arrayOfRecipes.length; i++)
+document.querySelector(".recipeList").innerHTML += "<button onclick='buttonDirect(" + i + ")'>Start Cooking</button>";
}
function buttonDirect(indexNum) {
localStorage.setItem("indexNumber", JSON.stringify(indexNum));
window.location.href = "/display.html";
buttonClicked();
}
function buttonClicked() {
JSON.parse(localStorage.getItem("indexNumber"));
console.log(indexNumber);
}
I am trying to get data (index number) from one function to carry on running after the HTML page has been changed.
Currently, I have a button which runs a function called "buttonDirect(indexNum)" I want this function to change from one page to another, hence why I used the window.location.href = "/display.html"; code within the function. After this, the page changes so I attempt to save the index number by saving it to local storage with the localStorage.setItem("indexNumber", JSON.stringify(indexNum)); code. Then since JavaScript reads the code from top to bottom, I tried to make it run the buttonClicked(); function after the page has changed so that it doesn't run until the next page has loaded. That way, I can retrieve the index number on the next page using JSON.parse(localStorage.getItem("indexNumber")); and then console log that number with console.log(indexNumber);.
I quickly realised that this will not work, because the buttonClicked() function will run before the page actually changes, meaning that the indexNumber will not get logged once the page changes. What is the best way to achieve what I am trying to do?
It looks like buttonClicked() won't get called because you would have left the page.
You can, when the page loads, get the data you want from local storage:
window.onload = function() {
const indexNumber = JSON.parse(localStorage.getItem("indexNumber"));
console.log(indexNumber);
}
(I added a variable for the result of JSON.parse.)
By the way, on the fourth line, I don't know if the + there is a typo
+document.querySelector...
^

Returning empty string on a input that has a value

I have a date input in my page, which I'm using Daterangepicker framework to populate it.
Here is the code of how I start my page!
$(function(){
startSelectors();
var variaveis = returnInputVars();
var rede = variaveis[0];
var codLoja = variaveis[1];
var period = variaveis[2];
console.log('1.'+rede+' 2.'+codLoja+' 3.'+period);
});
function returnInputVars(){
var rede = $("#dropdown-parceria").val();
var codLoja = $("#dropdown-loja").val();
var periodo = $("#datepicker-range").val();
return [rede, codLoja, periodo];
};
The function startSelectors() is set to start my datepicker and other fields, which is working perfectly. After it, I create a var called "variaveis" to fill
with the values of each field because I will use then later (this functions also works perfectly at other scripts of my page).
Running the page, my console returns this:
The funny thing is, if I type at the console this, the value is shown, just while starting the script is does not work!
Anybody experienced something like this?
***UPDATE
Adding this script to my start function:
console.log($("#datepicker-range"));
The value is shown, but the second console.log don't:
EDIT 1. FIDDLE (Suggested by #halleron)
To ensure things are loaded in the correct order, it is useful to apply a page sniffer code snippet that will scan the page continuously until a condition is met, or until a preset counter limit is reached (to prevent strain on browser memory). Below is an example of what I typically use that would fit your scenario.
I think because you are dealing with asynchronous loading, you can't have a global variable that holds the values in a global scope without an interval to detect when it can be used. Otherwise, it will attempt to read the variable when it is not yet ready.
You can invoke functions anywhere you like. But I would keep all of your variables contained within the page_sniffer_2017() because that is a controlled environment where you know that everything successfully loaded and you know that the variables are ready to be accessed without error.
That way, regardless of connection speed, your functions will only fire when ready and your code will flow, sequentially, in the right order.
Within the ajax success options, always add a class to the body of the document that you can search on to determine if it has finished loading.
$(document).ready(function() {
page_sniffer_2017();
});
function page_sniffer_2017() {
var counter = 0;
var imgScanner = setInterval(function() {
if ($("#datepicker-range").length > 0 && $("#datepicker-range").val().length && jQuery('body').hasClass('date-picker-successfully-generated')) {
var periodoDatepicker = $("#datepicker-range").val(); // ok
console.log(periodoDatepicker); // ok
var variaveis = returnInputVars(replaceDate(periodoDatepicker)); // ok
console.log(variaveis[0], variaveis[1], variaveis[2]);
//startNewSelectors(variaveis);
// start ajax call
generateData(variaveis[0], variaveis[1], variaveis[2]);
clearInterval(imgScanner);
} else {
//var doNothing = "";
counter++;
if (counter === 100) {
console.log(counter);
clearInterval(imgScanner);
}
}
}, 50);
}

Click on table causes multiple ajax operations are running with jQuery

after looking for a solution of a problem I may found the turning point and can define the problem.
My code uses jQuery and Ajax and is triggered on a click on a table cell. The output was and is a table which I refresh within an interval.
Well, when I clicked on a cell and then on another cell the output is switching between the outputs based on the transmitted value of cell A and cell B.
I took a look into firebug and, voila, got a sneak on the reason.
GET http://localhost/trading/getuser_exp.php?q=NYSE
GET http://localhost/trading/getuser_exp.php?q=NASDAQ
Both values are running parallel and this is wrong. I need a single value or, in other words, if I clicked on NYSE before, value is NYSE, then I click on NASDAQ, the value isn't NYSE anymore, but NASDAQ.
The code is use is
$(document).ready(function(){
$(".information").click(function () {
var str = $(this).closest("tr").find("#nr").text();
window.setInterval(function(){
$.get("getuser_exp.php",
{ q:str },
function(data) { $('.stock').html(data);
} //function data
);
}, 3000);
}); //information click
}); //document ready
Now what causes the multiple firing? In my eyes - frank speaking a beginner - nothing is multiple firing or that is accepting multiple values. Whatever it is, I will learn.
Thank you for any assistance and help.
You need to clear the old interval and start a new one. This is why you get multiple firings as each click starts a new interval timer.
$(document).ready(function(){
var timer = null;
$(".information").click(function () {
var str = $(this).closest("tr").find("#nr").text();
if(timer!=null) {
clearInterval(timer);
}
timer = window.setInterval(function(){
$.get("getuser_exp.php",
{ q:str },
function(data) {
$('.stock').html(data);
}
);
}, 3000);
});
});

Jquery load content then refresh every 2 second

i am having trouble solving this, i'm trying to load a page which process a variable given by an input form then show the content based on the input, this worked fine, but i am also trying to refresh and update that input every 2 seconds
Below are my codes
<script>
$(document).ready(function(){
function getData(){
$("#dateslot").change(function(){
var inputField= $('#dateslot').val();
$("#timeslot").load('burgerorder_check.php?dateselect='+inputField);
});
setTimeout(getData,1000);
};
getData();
});
</script>
I'm trying to create a function that if someone else picked that, you won't be able to, which i successfully coded but not for the refresh part.
You have the methods and variables in the wrong order. You should probably set a variable outside the getData scope that can change at anytime, then just use that variable when fetching data.
Also, use setInterval if you want to repeat the function. setTimeout is simply a delay.
var val; // the select value is stored here
$("#dateslot").change(function(){
val = $(this).val(); // change the value
}
setInterval(getData,1000);
getData();
function getData(){
if ( val ) {
$("#timeslot").load('burgerorder_check.php?dateselect='+val);
}
}

Autorefresh div with javascript

I have been looking around for the simplest way to refresh a particular div on my page, automatically, every x seconds.
So far I've got:
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('time').innerHTML = Date();
}
However the last part where the innerHTML is set to the date function is what I'd like replaced by the content of the "time" ID, and not an actual date print.
I know I could load an iframe, or externa html page, but I would like to simply call upon an existing div on the page instead of having to change the existing content. Is that possible?
Thanks!
Edit: What I mean is I have a a div that looks like this on the page:
Some stuff
I would like to have that div refreshed every x seconds, so yes, you may ignore the Date() part of my example, I simply found that code as is but when I tried to remove the .innerHTML part it just does nothing, I think lol!
Are you looking for something like this?
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
var now = new Date();
document.getElementById('time').innerHTML = now.getHours() + ":" + now.getMinutes() + ":" +now.getSeconds();
}
</script>
NOTE: The OP is actually wanting to reload a script in an ad service already included on the page. The following does not help with this; however, due to the way the question was asked, I'm leaving this answer since I think it could help others looking for the following type of solution. Just be aware this does not demonstrate how to "rerun" already included (presumably global and non-function'd) code.
Say I have the following div I'd like to dynamically refresh:
<div id="refresh">Refreshes...</div>
jQuery offers the $.ajax group of functions that allow you to dynamically request a page and use the response as HTML. For instance:
$(document).ready(function(){
var $refresh = $('#refresh'),
loaded = 1,
data = {
html: $.toJSON({
text: 'some text',
object: {}
}),
delay: 3
};
var refresh = function(){
$.ajax({
url: "/echo/html/",
data: data,
type: "GET",
success: function(response) {
$refresh.html($refresh.html() + '<br/>#' + loaded);
loaded++;
setTimeout(refresh, 3000);
}
});
};
refresh();
});
http://jsfiddle.net/Ah3jS/
Note, I'm using jsFiddle's echo/html/ functionality here as well. The data variable is tuned to working with this for demonstration purposes. In reality, the data sent with the request is either GET or POST variables like you work with normally. Also, I don't use response in success, but that's because it doesn't return anything in jsFiddle's demo mode.
jQuery make's this stuff pretty easy. Really, I'd think about using it instead of most other approaches (requirements notwithstanding).

Categories