json call does'nt update in IE 10 - javascript

I use this tiny script to feed a playlist and updates it every 20 sec. - for some reason it does'nt update in ie10 (and older versions too, I guess) - I failed to see where it goes wrong, any ideas...?
function playlist() {
$.getJSON("/playlist/", function (data) {
$("#play-now-arti").empty();
$("#play-now-title").empty();
$("#last-played").empty();
var i = 0;
$.each(data.PlayHistory.PlayInfo, function (index, value) {
var arti = value["ARTI"];
var title = value["TITLE"];
i++;
if (i == 1) {
$("#now-playing-artist").html(arti);
$("#now-playing-song").html(title);
}
else if (i > 1 && i < 8) {
$("<li>" + arti + " - <span>" + title + "</span></li>").appendTo("#last-played");
}
});
});
setTimeout(playlist, 20000);
};
playlist();

It was caching, indeed... - by adding "$.ajaxSetup({ cache: false });" to my function IE now updates just like the other browsers...
function playlist() {
$.ajaxSetup({ cache: false });
$.getJSON("/playlist/", function (data) {
$("#playlist").empty();
var i = 0;
$.each(data.PlayHistory.PlayInfo, function (index, value) {
var arti = value["ARTI"];
var title = value["TITLE"];
var spotify = value["Spotify"];
i++;
if (i == 1) {
$("<li class=\"jp-playlist-current\"><div tabindex=\"0\" class=\"jp-playlist-item jp-playlist-current\"><span class=\"jp-artist\">" + arti + ":</span><img src=\"/img/spotify.png\" style=\"border: 0;\" /><br><span class=\"jp-title\">" + title + "</span></div></li>").appendTo("#playlist");
}
else {
$("<li><div tabindex=\"0\" class=\"jp-playlist-item\"><span class=\"jp-artist\">" + arti + ":</span><img src=\"/img/spotify.png\" style=\"border: 0;\" /><br><span class=\"jp-title\">" + title + "</span></div></li>").appendTo("#playlist");
}
});
});
setTimeout(playlist, 200000);
};
playlist();

Related

Is there a way to have multiple inline configured ckeditors with single toolbar DOM element

An inline configured ckeditor has its toolbar attached to document body. Unless the user didn't focus the editor the toolbar is hidden. If we have multiple inline editors on same page, there will be the same number toolbar DOM elements attached to the body - each one with specific identifier. My question is, if there is a way to have a single toolbar DOM element for multiple inline ckeditors? I know (and I'm using in different context) the shared space plugin which does that, but the drawback is that one should provide an element to which the single toolabar would be attached. That's OK, but it is static and stays at the place where it's placed in the DOM order and I'd like it to be repositioned next to the currently focused editor.
Seems like I either have to use the default inline behavior or to use the shared space plugin and to reposition the single toolbar instance myself.
Any ideas on this issue or something I'm missing?
No, every CKEditor creates its own toolbar. But you can create your own plugin for this which is actually just displaying the toolbar of the active element. I have created one have a look. You do require to configure the your editor config too.
CKEDITOR.plugins.add('grouplabel', {
init : function(editor) {
function getCorrespondingName(no) {
var tempNo = 0;
for (var i = 0; i < editor.config.toolbar.length; i++) {
if (editor.config.toolbar[i].groupName != undefined) {
if (tempNo == no) {
return i;
}
tempNo++;
}
}
}
function toggleGroupDisplay(evt) {
if (evt.data.isMinimized) {
resetAllAbsolute();
$(this).find(".absoluteToolCont").toggleClass("displayNone");
} else {
$('.' + evt.data.grpID).each(function() {
toggleGroupDisplayInd(this)
});
}
}
function resetAllAbsolute() {
$(".absoluteToolCont").addClass("displayNone");
}
function toggleGroupDisplayInd(obj) {
var idM = $("#" + obj.id).parent().attr("id");
$("#" + idM + "> span").toggleClass("displayNone");
$("#" + idM).toggleClass("toggleMargin");
$("#groupLabel_" + idM).toggleClass("toggleMargin");
$("#groupLabelArrowBtn_" + idM).toggleClass("groupLabelArrowDown");
}
var openContainerArray = [ "CHARACTER", "TEXT ALIGN" ];
function createMainGroups() {
for (var j = 0; j < editor.toolbox.toolbars.length; j++) {
var grpId = editor.toolbox.toolbars[j].id;
var conNo = getCorrespondingName(j);
var isGroup = editor.config.toolbar[conNo].groupNR;
if (!isGroup) {
createMainGroup(conNo, grpId);
}
}
}
function createMainGroup(conNo, grpId) {
// console.log(conNo, grpId)
var name = editor.config.toolbar[conNo].groupName[0];
var className = editor.toolbar[conNo].name;
var name = editor.config.toolbar[conNo].groupName[0];
var elementDiv = groupLabelElementDiv(grpId, className);
var textDiv = "<div class='textGroupLabel'></div>";
var arrowDiv = "<div id='groupLabelArrowBtn_" + grpId
+ "' class='groupLabelArrowUp'></div>";
$("#" + grpId).addClass("editorGroup transitionType");
if (editor.config.showIconOnly) {
detachAndMakeAbsolute(grpId);
}
$("#" + grpId).prepend(elementDiv);
$("#groupLabel_" + grpId).append(textDiv);
if (!editor.config.showIconOnly) {
$("#groupLabel_" + grpId).append(arrowDiv);
}
addNameOrIcon(editor, name, grpId);
$(" #groupLabel_" + grpId).unbind("click").bind("click", {
grpID : "groupLabel_" + className,
isMinimized : editor.config.showIconOnly
}, toggleGroupDisplay);
var bool = false;
if (!editor.config.showIconOnly) {
for (var k = 0; k < openContainerArray.length; k++) {
if (name == openContainerArray[k]) {
bool = true;
}
}
}
showGroup(bool, grpId);
}
function detachAndMakeAbsolute(grpId) {
var divId = "absoluteToolCont_" + grpId
var absoluteDiv = "<div class='displayFlexAbsolute"
+ " absoluteToolCont' id='" + divId + "'></div>";
$("#" + grpId).prepend(absoluteDiv);
var detachedDiv = $("#" + grpId + "> span").detach();
// console.log(detachedDiv)
detachedDiv.appendTo("#" + divId);
resetAllAbsolute();
}
function showGroup(bool, grpId) {
if (!bool) {
$("#" + grpId + "> span").toggleClass("displayNone");
$("#" + grpId).toggleClass("toggleMargin");
$("#groupLabel_" + grpId).toggleClass("toggleMargin");
$("#groupLabelArrowBtn_" + grpId).toggleClass(
"groupLabelArrowDown");
}
}
function addNameOrIcon(editor, name, grpId) {
var groupName = $("#groupLabel_" + grpId + ">.textGroupLabel");
var divId = "absoluteToolCont_" + grpId
if (!editor.config.showIconOnly) {
groupName.text(name);
} else {
var clsName = name.replace(/ /g, '');
var detachedDiv = $("#" + divId).detach();
$("#groupLabel_" + grpId).prepend(detachedDiv);
groupName.html("<div class='iconToolbar " + clsName
+ "'></div>");
var overFlowRObj = "#cke_" + editor.name + " .cke_inner "
+ ".cke_top";
$(overFlowRObj).addClass("cke_top_overflow");
}
}
function groupLabelElementDiv(grpId, className) {
var elementDiv = "<div id='groupLabel_" + grpId
+ "' class='groupLabel transitionType groupLabel_"
+ className + "'></div>";
return elementDiv;
}
function createSubGroup() {
var loopVar = 0;
var divEle = '<div class="subGrpLabel textGroupLabel">' + "Font"
+ '</div>';
/*
* for (var k = 0; k < editor.toolbar.length; k++) { if
* (editor.toolbar[k] != "/") { for (var l = 0; l <
* editor.toolbar[k].items.length; l++) { if
* (editor.toolbar[k].items[l].type == "separator") { //
* console.log("sep") // $(editor.toolbar[k].items[l]).text("name"); } } } }
*/
}
editor.on('destroy', function() {
/* alert(this.name) */
var undoName = "undoRedoCont" + editor.name;
$("#" + undoName).remove();
});
editor.on('instanceReady', function() {
// console.log(previewSeen);
$("#universalPreloader").addClass("displayNone");
createMainGroups();
createSubGroup();
focusEvent();
undoRedoButtonSeprator();
});
function undoRedoButtonSeprator() {
var undoRedoContEle = "<div class='urcEle' id='undoRedoCont"
+ editor.name + "'></div>";
$("#undoRedoContSetParent").append(undoRedoContEle);
var ele = $("#" + editor.ui.instances.Undo._.id).detach();
$("#undoRedoCont" + editor.name).append(ele);
$(ele).addClass("cke_button_75px");
ele = $("#" + editor.ui.instances.Redo._.id).detach();
$("#undoRedoCont" + editor.name).append(ele);
$(ele).addClass("cke_button_75px");
$("#undoRedoCont" + editor.name).addClass("displayNone");
}
function focusEvent() {
var editorObj = /* parent. */$("#cke_wordcount_" + editor.name);
editorObj.addClass("displayFlexRelative").addClass("displayNone")
.addClass("vertical-align-middle").addClass(" flexHCenter")
.css("width", "160px");
var undoRedoCont = /* parent. */$("#undoRedoCont" + editor.name);
undoRedoCont.addClass("displayNone");
editor.on('focus', function(e) {
onFoucs(e);
});
editor.on('blur', function(e) {
onBlur(e);
});
}
function onBlur(e) {
var editorObj = /* parent. */$("#cke_wordcount_" + e.editor.name);
editorObj.addClass("displayNone");
$("#undoRedoCont" + editor.name).addClass("displayNone");
$("#dummyUNDOREDO").removeClass("displayNone");
resetAllAbsolute();
/*
* if (e.editor.config.customInline) {
* $("#toolbarEditorInline").addClass("displayNone"); }
*/
}
function onFoucs(e) {
var editorObj = /* parent. */$("#cke_wordcount_" + e.editor.name)
editorObj.removeClass("displayNone");
$("#undoRedoCont" + editor.name).removeClass("displayNone");
$("#dummyUNDOREDO").addClass("displayNone");
/*
* if (e.editor.config.customInline) {
* $("#toolbarEditorInline").removeClass("displayNone"); }
*/
}
CKEDITOR.document.appendStyleSheet(CKEDITOR.plugins
.getPath('grouplabel')
+ 'css/style.css');
}
});

Variable isn't changing in for loop - JavaScript

Why is this outputting each feedName as the same name (MedryBW)? I've spent a while messing around with it, can't figure it out. I want it to output the name of the feed in each iteration of the loop rather than repeating the same one over and over again. Thanks everyone.
var feeds = ["Towellie", "TrumpSC", "TeamSp00ky", "TwitchPlaysPokemon", "Widgitybear", "AriaBlarg", "TheMexicanRunner", "OPNerd", "rabbitbong", "Wingsofdeath", "MedryBW"];
$(document).ready(function(){
for(x = 0; x < feeds.length; x++){
var feedName = feeds[x];
$.getJSON('https://api.twitch.tv/kraken/streams/' + feeds[x] + '?callback=?', function(data) {
if(data.stream === null){
$('#feeds').append("<p>" + feedName + " is offline </p>");
} else {
$('#feeds').append("<p>" + feedName + " is streaming " (data.stream.game) + "/<p>");
}
});
}
});
Because callback function runs much later, not in the loop, and it just gets variable value after loop has finished (last value), use bind function to pass variable to the function
var feeds = ["Towellie", "TrumpSC", "TeamSp00ky", "TwitchPlaysPokemon", "Widgitybear", "AriaBlarg", "TheMexicanRunner", "OPNerd", "rabbitbong", "Wingsofdeath", "MedryBW"];
$(document).ready(function() {
for(x = 0; x < feeds.length; x++){
var feedName = feeds[x];
$.getJSON('https://api.twitch.tv/kraken/streams/' + feeds[x] + '?callback=?', function(feedName, data) {
if (data.stream === null) {
$('#feeds').append("<p>" + feedName + " is offline </p>");
}else{
$('#feeds').append("<p>" + feedName + " is streaming " + (data.stream.game) + "/<p>");
}
}.bind(this, feedName));
}
});
As you have written Ajax in for loop , The success callback executes after for loop has executed
var feeds = ["Towellie", "TrumpSC", "TeamSp00ky", "TwitchPlaysPokemon", "Widgitybear", "AriaBlarg", "TheMexicanRunner", "OPNerd", "rabbitbong", "Wingsofdeath", "MedryBW"];
$(document).ready(function() {
feeds.forEach(function(feedName) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + feedName + '?callback=?', function(data) {
if (data.stream === null) {
$('#feeds').append("<p>" + feedName + " is offline </p>");
} else {
$('#feeds').append("<p>" + feedName + " is streaming " + (data.stream.game) + "/<p>");
}
});
});
})
THe Above change will work
You can achieve this by.
var feeds = ["Towellie", "TrumpSC", "TeamSp00ky", "TwitchPlaysPokemon", "Widgitybear", "AriaBlarg", "TheMexicanRunner", "OPNerd", "rabbitbong", "Wingsofdeath", "MedryBW"];
$(document).ready(function(){
var divText;
for(x = 0; x < feeds.length; x++){
var feedName = feeds[x];
$.getJSON('https://api.twitch.tv/kraken/streams/' + feeds[x] + '?callback=?', function(data) {
if(data.stream === null){
divText = divText + '<p>'+feedName+' is offline </p>';
}else{
divText = divText + '<p>'+feedName+' is streaming '+(data.stream.game) +'</p>'
}
});
}
$('#feeds').append(divText);
//or $('#feeds').html(divText);
})

Unresponsive Script Error in JS.erb File

Currently I have the Below code in a js.erb file in my ruby on rails project. What is happening is that the page is becoming unresponsive when this file is being used. Sometimes the #updates1 can have upwards of 100 records. is there a way to process the painting in the background and keep the UI responsive. With it the way it is the page becomes "locked up/unresponsive" for 10 sec to 1 minute. sometimes i get the warning of this page has become unresponsive.
My Code works just Takes A long time to process
Actual Code in the js.erb
var obj1 = {
"loads": <%= raw #updates1 %>
};
var count = 0;
var tab_keys = [];
$.each(obj1["loads"], function(k, v){
$.each(v, function(key, value) {
count++;
var addId = $('#' + key).dataTable().fnAddData(value);
var theNode = $('#' + key).dataTable().fnSettings().aoData[addId[0]];
theNode.nTr.setAttribute('id','row_' + value[0]);
$('#' + key).dataTable().fnAdjustColumnSizing();
tab_keys.push(key);
});
});
if (count > 0) {
var message = count + " More Loads!";
$.titleAlert(message, {
requireBlur:false,
stopOnFocus:false,
duration:8000,
interval:700
});
tab_keys = $.unique(tab_keys);
$.each(tab_keys, function(k, v){
var tab_key = v.replace(new RegExp("_load_results", "gi"), "");
var tab = 'a[href$="#tab_' + tab_key + '"]';
if ($(tab).parent().hasClass("ui-state-active") == true)
$(tab).css("font-weight","bold").parent().effect( 'highlight', {color: 'Blue'}, 7000);
else
$(tab).css("font-weight","bold").parent().css("background","#00D9D9").effect( 'highlight', {color: 'Blue'}, 7000);
});
if ( $('#prefs_can_be_screen_notified').val() == "1") {
playSound('/assets/'+$('#prefs_default_sound').val());
}
}
Results of what it is doing: BTW i cut the obj1 down in length for posting on here... It can sometimes be 100+ postings...
var obj1 = {
"loads": [{'25455_1431099504_load_results': ['13345499','2015-05-08 15:48:37 UTC','<abbr class=\"timeago\" title=\"2015-05-08 10:48:37\">1 minute</abbr>','Albuquerque, NM','Colorado Springs, CO','05/12','05/13','Full','Flatbed','','53']}, {'25455_1431099504_load_results': ['13345497','2015-05-08 15:48:37 UTC','<abbr class=\"timeago\" title=\"2015-05-08 10:48:37\">1 minute</abbr>','Gypsum, CO','Lincoln, NE','05/08','05/11','Full','Flatbed','','53']}]
};
var count = 0;
var tab_keys = [];
$.each(obj1["loads"], function(k, v){
$.each(v, function(key, value) {
count++;
var addId = $('#' + key).dataTable().fnAddData(value);
var theNode = $('#' + key).dataTable().fnSettings().aoData[addId[0]];
theNode.nTr.setAttribute('id','row_' + value[0]);
$('#' + key).dataTable().fnAdjustColumnSizing();
tab_keys.push(key);
});
});
if (count > 0) {
var message = count + " More Loads!";
$.titleAlert(message, {
requireBlur:false,
stopOnFocus:false,
duration:8000,
interval:700
});
tab_keys = $.unique(tab_keys);
$.each(tab_keys, function(k, v){
var tab_key = v.replace(new RegExp("_load_results", "gi"), "");
var tab = 'a[href$="#tab_' + tab_key + '"]';
if ($(tab).parent().hasClass("ui-state-active") == true)
$(tab).css("font-weight","bold").parent().effect( 'highlight', {color: 'Blue'}, 7000);
else
$(tab).css("font-weight","bold").parent().css("background","#00D9D9").effect( 'highlight', {color: 'Blue'}, 7000);
});
if ( $('#prefs_can_be_screen_notified').val() == "1") {
playSound('/assets/'+$('#prefs_default_sound').val());
}
}
The Above is ran from this AJax Script:
if (load_search_count > 0) {
$.ajax({
url: "/classics/0/refresh_load_tables",
type: "POST",
success: function (data) {
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
}

"Page Unresponsive" Error in Chrome when trying to GET files > 500kb

I am trying to get Log files in my application, and am using Ajax to do so.
The problem is that while using Chrome I constantly get 'Page Unresponsive' Errors when I try to load the files.
My application is working fine in Firefox, so I'm guessing this is a webkit issue.
I removed xhr because I heard chrome has a problem with it.
This is my code -
$.ajax(
{
type: 'GET',
url: "Logs/GetLogFile?option=" + logFile,
data: {},
success: function (data) {
var fileData = data;
cleanUp();
currentlyViewedFile = logFile;
var fileLines = fileData.split('\n');
var htmlString = '';
var lineCount = 0;
for (var i = 0; i < fileLines.length; i++) {
lineCount = lineCount + 1;
if (i == (highlightLine - 1)) {
htmlString += '<span id="highLoc" style="display:block"><font size="4" color="red">' + lineCount + '. ' + fileLines[i] + '</font></span>';
}
else {
htmlString += '<span class="spanClass">' + lineCount + '. ' + fileLines[i];
}
var combinedLine = fileLines[i];
var isNewLogLine = false;
var newLogLineCount = 0;
while (((i + newLogLineCount + 1) < fileLines.length) && (isNewLogLine == false)) {
var NextlogLine = fileLines[i + newLogLineCount + 1].split(' ');
isNewLogLine = isLogLine(NextlogLine[0]);
if (isNewLogLine == true) {
break;
}
htmlString += fileLines[i + newLogLineCount + 1];
combinedLine += fileLines[i + newLogLineCount + 1];
newLogLineCount = newLogLineCount + 1
}
i = i + newLogLineCount;
var logLine = combinedLine.split(' ');
var logMsgStartIndex = combinedLine.indexOf(logLine[5]);
var logMsg = combinedLine.substring(logMsgStartIndex);
var obj = {
lineNos: lineCount,
date: logLine[0],
time: logLine[1],
severity: logLine[2],
logClassName: logLine[4],
logMessage: logMsg
};
fileArray.push(obj);
if ((i % 1000) == 0) {
$("#textPlace").append(htmlString);
htmlString = '';
window.scrollTo(0, 2);
}
}
fileLines = null;
$("#fetchProgress").hide();
$("#textPlace").append(htmlString);
//highlight error location
var scrollX = $("#highLoc");
if (scrollX) {
if (!scrollX[0]) return;
var scrollDistance = '{ scrollTop: ' + scrollX[0].offsetTop + '}';
var distanceInJson = eval("(" + scrollDistance + ")");
$("#mainContentBox").animate(distanceInJson, 1);
}
},
///success function end
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
});
If anyone has any ideas on how to deal with this issue, please let me know.

Javascript - passing parameter to function which calls another function

Okay my title is a bit confusing but basically, I have a function and after that function is finished executing, it should do the given steps. Here is my javascript:
createSideTable(showThis, function() {
$('#' + showThis + 'Screen').slideDown('slow');
});
I want the createSideTable function to run all it's code before the step
$('#' + showThis + 'Screen').slideDown('slow');
can get executed. The createSideTable more or less just makes a side table fade in slowly. The function can be seen at the end of this post.
Normally, when I have a function which I want to execute all it steps and then execute other given steps, i'd do it like this
createSideTable(function() {
$('#' + showThis + 'Screen').slideDown('slow');
});
and it works, however, the createSideTable function needs a parameter (the parameter which it needs is showThis). So when I tried
createSideTable(showThis, function() {
$('#' + showThis + 'Screen').slideDown('slow');
});
it did create the sideTable however, this step
$('#' + showThis + 'Screen').slideDown('slow');
didn't get executed after it created the sideTable. How come?
This is my createSideTable function.
function createSideTable(test) {
var key = test.substr(test.length -1); //index of Heading
for (var i=0; i<window['headings' + key].length; i++) {
if (i == 0) {
$('#row' + i).addClass('subHeadingClicked');
}
$('#row' + i).text('').removeClass('column1invisible');
$('#row' + i).append(window['headings' + key][i]);
}
$('#sideTable').fadeIn(1500);
}
Add the callback parameter, and if it exists, call it at the end:
function createSideTable(test, callback) {
var key = test.substr(test.length -1); //index of Heading
for (var i=0; i<window['headings' + key].length; i++) {
if (i == 0) {
$('#row' + i).addClass('subHeadingClicked');
}
$('#row' + i).text('').removeClass('column1invisible');
$('#row' + i).append(window['headings' + key][i]);
}
$('#sideTable').fadeIn(1500);
if (callback) callback();
}
And you should be able to call it like this:
createSideTable(showThis, function() {
$('#' + showThis + 'Screen').slideDown('slow');
});
Edit -
The first example was showing how a callback works. You can execute the callback where ever you want... for example, if you want it to be executed after the fadeIn(), you could do this:
function createSideTable(test, callback) {
var key = test.substr(test.length -1); //index of Heading
for (var i=0; i<window['headings' + key].length; i++) {
if (i == 0) {
$('#row' + i).addClass('subHeadingClicked');
}
$('#row' + i).text('').removeClass('column1invisible');
$('#row' + i).append(window['headings' + key][i]);
}
$('#sideTable').fadeIn(1500, function() {
if (callback) callback();
});
}

Categories

Resources