Unresponsive Script Error in JS.erb File - javascript

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;
}

Related

How to parse Json response using JavaScript and populate field with specific data from the response

All I will start with, I am not strong in javascript but I am learning Javascript while taking a course. I am running into an issue ... I am trying to get the user first name and last name in a drop-down list based on the search the user provided. I was able to get the drop down to populate but I cannot seem to be able to parse the object to an actual string. I get the following results back:
[object Object],[object Object],[object Object],[object Object],[object Object]
Can any javascript expert help me resolve this?
Here is my JSON response
{
"users":[
{
"first_name":"khemlall",
"last_name":"mangal",
"image":{
"url":"https://chymeinuserupload.s3.amazonaws.com/uploads/user/image/1/KDFM_062.jpg"
},
"url":"/users/1"
},
{
"first_name":"Donald",
"last_name":"trump",
"image":{
"url":"https://chymeinuserupload.s3.amazonaws.com/uploads/user/image/2/2018-02-28_11_53_35-Step_2_of_4__Select_a_Logo_Design___LogoMaker_Customer_Service.png"
},
"url":"/users/2"
},
{
"first_name":"Renita",
"last_name":"mangal",
"image":{
"url":"https://chymeinuserupload.s3.amazonaws.com/uploads/user/image/3/20120426_food-1.jpg"
},
"url":"/users/3"
},
{
"first_name":null,
"last_name":null,
"image":{
"url":null
},
"url":"/users/4"
},
{
"first_name":null,
"last_name":null,
"image":{
"url":"https://chymeinuserupload.s3.amazonaws.com/uploads/user/image/5/2018-03-27_09_48_19-new_version_chymin__1___2_.png_-_Windows_Photo_Viewer.png"
},
"url":"/users/5"
}
]
}
javascript code
$(document).on('change', '#createcampaign_decisionmaker', function() {
var input_state = $(this);
console.log("khemlall starts")
var decisionmaker = $("#decisionmaker");
if ($(this).val() == "") {
decisionmaker.html("");
} else {
$.getJSON('/search/', function(data) {
// cities_of_state.empty();
var results = data;
console.log( results);
alert(data.users.first_name)
// console.log(data.getValue("first_name"))
var opt = '<option value="" selected="">list of user</option>';
if (data.length == 0) {
} else {
$.each(data, function(i, elm) {
console.log("loggo" + i);
opt += '<option>' + elm + '</option>';
decisionmaker.html(opt);
console.log('I' + i);
});
}
});
}
});
maybe like this
$(document).on('change', '#createcampaign_decisionmaker', function() {
var input_state = $(this);
var decisionmaker = $("#decisionmaker");
if ($(this).val() == "") {
decisionmaker.html("");
} else {
$.getJSON('/search/', function(data) {
if (data.length > 0) {
var options = data.map(function(d) {
return "<option value=\"" + d.url + "\">" + d.first_name + " " + d.last_name + "/<option>";
});
options.unshift("<option value=\"\" selected>list of users</option>");
decisionmaker.html(options.join(""));
} else {
decisionmaker.html(""); // maybe indicate that there are no users if needed
}
});
}
});
This is what seems to work for me, user3808826 I tried your code and it doesn't seem to return anything for me as the result
$(document).on('change', '#createcampaign_decisionmaker', function() {
var input_state = $(this);
console.log("khemlall starts")
var decisionmaker = $("#decisionmaker");
if ($(this).val() == "") {
decisionmaker.html("");
} else {
$.getJSON('/search/', function(data) {
var results = data;
var opt = '<option value="" selected="">list of user</option>';
if (results.length == 0) {
} else {
//$.each(data.users, function(index, value)
//{console.log("index" + index + ": " + value)})
$.each(results.users, function(index, value) {
opt += '<option>' + value.first_name + " " + value.last_name + '</option>';
decisionmaker.html(opt);
});
}
});
}
});

delete from database with javascript

I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.

json call does'nt update in IE 10

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();

"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.

problem ajax load with autocomplete.?

i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it

Categories

Resources