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>
Related
I have an html table on a page with raws that have 'urls', I'm trying to fetch one url at a time from a random row, however my code returns url as http://www.test.com/products/product-namehttp://www.test.com/products/product-name.json, as you can see it returns url twice, one without json and other with json data, hence I'm getting 404.
I just need the .json URL, not the first part.
How do I get rid of the first url which is not json?
Here's the code.
$(document).ready(function() {
$(document).on('click', '#closepopup', function() {
$("#popup").removeClass('popupslidein')
});
var tablelink = "https://test.com/pages/product-listing-for-popups.json"; //products url for json data
$.getJSON(tablelink, function(data) {
var table = data.page.body_html;
$('#popuptable').append(table);
startthepopups()
});
var suburbink = "https://test.com/pages/product-listing-suburbs-for-popups"; //suburb names in table rows
$.getJSON(suburbink, function(data) {
var suburb = data.page.body_html;
$('#popupsuburb').append(suburb)
});
var namelink = "https://test.com/pages/product-listing-names-for-popups"; //names in table rows
$.getJSON(namelink, function(data) {
var name = data.page.body_html;
$('#popupname').append(name)
});
function startthepopups() {
var popupstay = 10000;
var popuptrigger = 100000;
function triggerpopup() {
var getrandomtd = Math.floor((Math.random() * $('#popuptable tr').length) + 1);
var link = $('#popuptable tr:nth-child(' + getrandomtd + ')').text();
console.log(link);
var productname = '';
var getrandomsuburbtd = Math.floor((Math.random() * $('#popupsuburb tr').length) + 1);
var suburblink = $('#popupsuburb tr:nth-child(' + getrandomsuburbtd + ')').text();
var getrandomnametd = Math.floor((Math.random() * $('#popupname tr').length) + 1);
var randomname = $('#popupname tr:nth-child(' + getrandomnametd + ')').text();
$.getJSON(link + '.json', function(data) {
productname = data.product.title;
imagelink = data.product.images[0].src;
if (!$("#popup").hasClass("popupslidein")) {
$('#popupsomeone span.name').empty().append(randomname);
$('#popupsomeone span.location').empty().append(suburblink);
$('#popupimage').css('background-image', 'url(' + imagelink.split('.jpg')[0] + '_small.jpg)');
$('#popupproduct a').attr('href', link).empty().append(productname);
$("#popupagotext").empty().append(Math.round(Math.random() * 15 + 10));
$("#popup").addClass('popupslidein');
setTimeout(function() {
$("#popup").removeClass('popupslidein')
}, popupstay);
}
});
}(function loop() {
var random = Math.round(Math.random() * 10) * 100000 + popuptrigger;
setTimeout(function() {
triggerpopup();
loop()
}, 60000)
}());
}
});
$.getJSON() has a tendency to append your current url to the path you pass it if it thinks it's relative. To make this work, you could try to use $.getJSON() like so. Keep in mind, the protocol used will be the current page this code lives on.
$.getJSON('//test.com/pages/product-listing-for-popups.json')
I also noticed that nowhere in your code do you have a url for http://www.test.com/products/product-name.json, are you sure you're sharing the correct snippet of code?
Working Demo
The following two ways of using $.getJSON() with a fully qualified url work perfectly fine:
$(document).ready(function() {
var url = "https://jsonplaceholder.typicode.com/todos/1";
// Example 1
$.getJSON(url)
.done(function( data ) {
console.log(data);
});
// Example 2
$.getJSON(url, function(data) {
console.log(data)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to get a *.srt file and parse it with this script: Parse a SRT file with jQuery Javascript.
I've got a problem with the AJAX call blocking rest of the JS code. I tried to add syncs, set timeout, I wrapped it into a setTimeout function, tried with another *.srt file, but still it's not working. It doesn't throw error, it alerts end dialog, parsed lines are stored in variable but another scripts are frozen.
var subtitles = [];
$.ajax({
method: "GET",
url: '{% static "file.srt" %}',
async: true,
error: function(data) {
alert("error");
},
success: function(data) {
function strip(s) {
return s.replace(/^\s+|\s+$/g, "");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
srt = strip(srt);
var srt_ = srt.split('\n\n');
var cont = 0;
for (s in srt_) {
st = srt_[s].split('\n');
if (st.length >= 2) {
n = st[0];
i = strip(st[1].split(' --> ')[0]);
o = strip(st[1].split(' --> ')[1]);
t = st[2];
if (st.length > 2) {
for (j = 3; j < st.length; j++)
t += '\n' + st[j];
}
//define variable type as Object
subtitles[cont] = {};
subtitles[cont].number = n;
subtitles[cont].start = i;
subtitles[cont].end = o;
subtitles[cont].text = t;
document.body.innerHTML += " (" + subtitles[cont].start + " - " + subtitles[cont].end + " ) " + subtitles[cont].text + "<br>";
}
cont++;
}
alert("end");
},
timeout: 2000,
});
Please help me.
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);
});
}
}
This is my javascript code, I checked it in Chrome and its not giving me an error
window.onload = function() {
var timeClock = function (){
setTimeout("timeClock()", 1000);
var timeObj = new Date();
var currTime = timeObj.getHours(); + " : " + timeObj.getMinutes(); + " : " + timeObj.getSeconds();
document.getElementById("#clock-container").innerHTML = "asd";
}
}
I am trying to update this div with the current system time
<div id="clock-container"></div>
You have multiple logic and other mistakes.
You are attempting to register the callback, but your setTimeout is in the callback itself. Move setTimeout("timeClock()", 1000); outside the callback.
Presumably you also want to replace setTimeout with setInterval to have the clock continuously update, and also avoid having to call setTimeout in the callback.
There's also no reason to use a string to call timeClock, so use setInterval(timeClock, 1000); instead and avoid the evil that is code evaluation.
document.getElementById("#clock-container") should be document.getElementById("clock-container").
Your currTime expression has several ; where they don't belong, fix those and you can use this variable instead of your string.
You can also call timeClock immediately after load, to avoid waiting for the first interval.
Working Example:
window.onload = function() {
var timeClock = function (){
var timeObj = new Date();
var currTime = timeObj.getHours() + " : " + timeObj.getMinutes() + " : " + timeObj.getSeconds();
document.getElementById("clock-container").innerHTML = currTime;
}
setInterval(timeClock, 1000);
timeClock();
}
<div id="clock-container"></div>
I am not sure what you're trying to do but The script should be
window.onload = function() {
var timeClock = function (){
var timeObj = new Date();
var currTime = timeObj.getHours() + " : " + timeObj.getMinutes() + " : " + timeObj.getSeconds();
document.getElementById("clock-container").innerHTML = currTime;
setTimeout(timeClock, 1000);
}
timeClock();
}
I've been working on a chat application and now I need to scroll automatically when a message appears.
I've tried different things but they do not work unfortunately.
So this is my main.js code:
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "/refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
var message = $('#view_ajax');
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div>(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
message.html(data);
message.scrollTop(message[0].scrollHeight);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "/submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
I've used
var message = $('#view_ajax');
message.html(data);
message.scrollTop(message[0].scrollHeight);
I really have no clue how jQuery works. I've tried a couple of things before this but it didn't work also.
Do you have any suggestion? Any advice?
Do you need any more information? Feel free to ask!
Give each message an ID, as follows:
<div id="msg-1234">
Then you can scroll to this element using this jQuery:
$('html, body').animate({ scrollTop: $('#msg-1234').offset().top }, 'slow');
Alternatively, put a div at the bottom of your chat:
<div id="chat-end"></div>
And scroll to this ID instead.
JSFiddle Demo