JSON file / script preventing page from displaying. - javascript

I have a JSON file that is approx 500 lines long. The script that reads in the file is the first thing to happen when the page is loaded. The script works perfectly. It updates a drop down box automatically depending on a users choice.
A moment ago I added an additional 50 lines or so to the JSON file, maintained correct syntax etc etc. When I reloaded the page there was nothing but a white screen, no error logs etc. I removed what I had added to the JSON and received the same white screen, I'd also reloaded the page after clearing cache and on different browsers, same thing.
I then commented out the script that calls the JSON, reloaded and voila, it's fine. I un-comment the script again so it is as it was and magic, it now works.
Can anyone explain what could be happening and how I might solve it please? I can't force it to happen again but that doesn't mean it won't.
Many thanks.
Simplified sample of JSON:
"angle" : [
{
"value":"degree",
"name":"Degree (deg)"
},
{
"value":"grad",
"name":"Grad (grad)"
}]
The script that calls it:
<script>
$.getJSON('JSON/conversionJSON.json', function(data){
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
}
});
});
});
</script>
Thanks

Related

PHP - Update Displayed Info Upon Changing PDF Canvas

I've been running into an issue while trying to update a script for a client. I'm still somewhat new to the industry, so I wanted to make sure I'm not missing anything.
I am attempting to edit a web page which displays a number of PDFs in canvas views. The issue arises when a user tries to switch which PDF they're viewing. The function that retrieves the PDFs has a setTimeout in place to get the content to reload every minute, as the PDFs themselves are updated with new data every 5 minutes and the users need to be able to monitor the data as it comes in. However, when switching from one PDF canvas to the next, I found that the PDF doesn't update. The only PDF that reloads and updates is the one whose canvas has been open. This is what I'm trying to change. I want the PDF display to update not only every minute, but also whenever a user switches which PDF they're viewing.
What this told me is that I need to add something that loads the PDFs again when switching canvas views. First, I tried taking the function that updates the PDFs and calling it whenever the user switches the canvas view. This seemed to work, but the issue ended up changing. The page would begin to reload more and more often the more times you would change canvas views - I'd assume because the setTimeout within the function had then been called more than once.
My second attempt was to make a new function that simply didn't have the setTimeout code and call that instead. I must have done something wrong however, because after calling that function in the code, none of the PDFs wanted to load at all.
I'll paste the code for the functions I need to work with below. Any help is appreciated, especially if I'm just missing something obvious. If you need any other details, let me know. Thank you to anybody who offers help.
function getReport(reportName, frameId) {
var params = {
report: reportName
};
$.post('/getReport.php', params, function(data){
if (data == "") {
window.location.href="/login.php";
return;
}
if (useBrowserViewer) {
$("#pdfFrame" + frameId).attr("data", "data:application/pdf;base64," + data);
} else {
displayPdf(data, document.getElementById("canvas" + frameId), 1);
if (frameId == "4") {
displayPdf(data, document.getElementById("canvas4Page2"), 2);
}
}
setTimeout(function() {
getReport(reportName, frameId);
}, 60*1000);
}).fail(function() {
console.log("Report not returned.");
setTimeout(function() {
getReport(reportName, frameId);
}, 60*1000);
});
}
function showReport(frameIdNum) {
if (useBrowserViewer) {
$(".pdfFrame").hide();
$("#pdfFrame" + frameIdNum).show();
} else {
$(".pdfCanvas").hide();
document.getElementById("canvas" + frameIdNum).style.display = 'block';
if (frameIdNum == "4") {
document.getElementById("canvas4Page2").style.display = 'block';
}
}
$(".link").removeClass("active");
$("#link" + frameIdNum).addClass("active");
}

Amend Javascript code to Print,Tab & enter

I'm very new to java script, and I have to amend this code to make a product work...If I can't, may end sending it back.
I've tried amending the code very basically.Changed Tab to Enter, and back again.
function processData (arrData)
{
var sData = DataToString(arrData);
Print("Data: " + sData);
if (!SendKeyStrokes (sData.replace(/\x00/g, " ") + "{TAB}"))
NotifyWarning("Ignoring keystrokes sent to TWedge. Please set focus to the target application.");
}
This will output the bar code and tab over to next cell.
I'm hoping its easy, but I would like to amend it to do..
Code,tab,Code,tab,Code,tab,Code,Tab,Code,ENTER

DOM elements are only sporadically created despite being loaded by ajax

This is a very specific problem and one that makes me particularly confused. The project in short: I'm working on a counseling website that gets data from an API and is loaded with AJAX. I'm now trying to get old, archived chats to be be preloaded and displayed with css on click in a menu.
Here's the problem: It works... but only about 1 in 3 times or after reload of the page. I don't understand how that can be, either it should work or it doesn't.
I checked and the data is always loaded (it has to because the current chat is opened first and always works)
So how can that be?
$.ajax({
type: 'POST',
url: '/vsbt/counselling/archive/',
data: {},
}).done(function(data) {
console.log('ajax /vsbt/counselling/archive/');
console.log(data);
//menu is created
$('#counselling_status').append('<ul class="archivedCounsellings"></ul>');
$('.archivedCounsellings').append('<h2>Archivierte Chats</h2>')
for (var i = 0; i < data.length; i++) {
//menu items are added
var that = data[i].messages[0].title;
$('.archivedCounsellings').append('<li class="' + that + '"><a>' + that + '</a></li>')
$('#vbst_communication_container').prepend($('<div class="counselling inactive ' + that + '" />')
.append($('<h2>' + that + '<h2>')));
//the messages are added with to classes for styling
data[i].messages.forEach(function(message) {
$("div." + that)
.append($('<div />')
.addClass(message.type)
.append($('<p />')
.text(message.message)))
});
//this doesn't work either, you can maybe tell me why, but that's not the issue
$('.counselling').data("status", [i]);
}
$(".archivedCounsellings").append('<li class="aktuell"><a><br>Zur aktuellen Beratung</a></li>');
//click event to toggle the displayed counseling
$('.archivedCounsellings li').click(function() {
$('.counselling').addClass('inactive');
$('div .' + $(this).attr('class')).removeClass('inactive');
//workaround which works, but isn't really acceptable
// no load workaround
// if($('.openCounselling').siblings().length == 0){
// window.location.reload();
// }
// $('.statusDisplay').text($('#job_status_' + $(this).attr('class')).data("status"));
// console.log($('div .' + $(this).attr('data-status')));
});
PS. I'm aware of the typo in 'counselling'
PPS. if you find a mistake that obviously makes it fail that probably happend while copying since, remember, it does work sometimes.
Ok so if anyone ever encounters this problem: I was just explained AJAX a little bit closer and basically AJAX sends out all the requests more or less simultaneously. Whatever happens in the done function happens after that, hence the successful data request.
What I did, was initiate the container for said elements in a different function. So occasionally that one was a little bit slower and there was no place to append my elements to --> no error, just nothing happened.
It's unlikely that anyone will see this, since it's very specific, but maybe this'll help someone, at least i know better now

Create CSV from html using flash, javascript, classic asp

Let me start by stating that my end goal is to create an Export to Comma Separated File (.csv) or Export to Excel button on a page of our site. Our site currently has a search mechanism that returns the data in XML. That XML is loaded into a Microsoft.XMLDOM object.
Dim objXMLDom
Set objXMLDOM = Server.CreateObject("Microsoft.XMLDOM")
...
Function LoadXML(strXML)
objXMLDOM.loadXML(strXML)
end function
This XML data is parsed into a variable called myData and is displayed in an HTML Grid using different columns & rows. Like I said above, ideally I would like to add a button to the page that can export to csv or Excel. I've searched around and found that this is not an easy task when the code is in Classic ASP...so I found a semi-work around.
The workaround is to use Downloadify. It's a jquery/flash script that allows you to copy code into the HTML of a DOM element and then pull that data back out all on the client side. It works for the most part...the only problem I'm having is adding in a new line character. I think it gets removed going into HTML and back out again.
Here's the code for how I put data into the element
for (i = 0; i < <%=RowCount %>; i++) {
parent.document.getElementById('data').innerHTML += '\n';
for (j = 0; j < <%=columnCount%>; j++) {
parent.document.getElementById('data').innerHTML += myData[i][j];
parent.document.getElementById('data').innerHTML += ',';
}
};
Here's what I use to pull it back out:
function load() {
Downloadify.create('downloadify', {
filename: function() {
return document.getElementById('filename').value;
},
data: function() {
return document.getElementById('data').value;
},
onComplete: function() { alert('Your File Has Been Saved!'); },
onCancel: function() { alert('You have cancelled the saving of this file.'); },
onError: function() { alert('You must put something in the File Contents or there will be nothing to save!'); },
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
}
);
}
I really don't know very much Flash, but I've tried putting in different strings ('<br>', '
', even ";:;" ) and replacing them in the data : function part using Flash's replace method, but it seems to hang and never finish processing (i think this is because I needed to put the replace method in a while loop since the replace method only replaces one instance and I have many).
Any help will be appreciated. Thank you in advance.
why don't you have the ASP create a .csv file along with the html page? It seems like that would be a lot easier.
I had a problem like this awhile back when I was using Flash and ASP together.
I remember calling ASP from Flash and it hanging. I THINK the fix was to add a "response.end" to the end of the ASP page. That seemed to tell the server, "Done. Back to Flash now." Sorry I can't be more sure. It was a long time ago and I can't find the code.

How to do Threading in Javascript

So I have a large JSON object i'm returning from the server, then building a datatable from it and displaying it on the form. This usually takes a few seconds.. so I was thinking of a loading bar.
I have the logic behind the loading bar, however the loop that builds the hmtl data is locking down the browser and I cannot call out to the element i need to update.
Here is my function to do this:
function buildDataTable(db_table, container_id) {
var $pb = $("<div id=\"progress-bar\"></div>");
$(container_id).html($pb);
$pb.progressbar({
value: 0
});
$.post("post location", {
view: "all"
}, function (data) {
var headers = "";
var contents = "";
var jsonObject = $.parseJSON(data);
var tik = Math.round(jsonObject.length / 100);
for (key in jsonObject[0]) {
headers += "<th>" + key.replace(" ", " ") + "</th>";
}
for (i in jsonObject) {
contents += "<tr>";
for (j in jsonObject[i]) {
contents += "<td class=\"border-right\">" + jsonObject[i][j] + "</td>";
}
contents += "</tr>";
if(Math.round(i/tik) == i/tik) {
/* if I run the alert (between popups) i can see the progressbar update, otherwise I see no update, the progressbar appears empty then the $(container_id) element is updated with the table i've generated */
alert('');
$pb.progressbar("value",i/tik);
}
}
var html = "<table cellpadding=\"5\" cellspacing=\"0\"><thead><tr>" + headers + "</tr></thead><tbody>" + contents + "</tbody></table>";
$(container_id).html(html);
$(container_id).children("table:first").dataTable({
"bJQueryUI": true,
"sScrollX": "100%"
});
});
}
[Added my comment as an answer]
JavaScript is single threaded. You'll have to break your work up into pieces and call them in sequence using "setTimeout" to allow the GUI to update during processing (in between your calls) but even then the browser will still seem somewhat unresponsive.
You can try using WebWorker: https://developer.mozilla.org/en/DOM/Worker
Thus worker are executed in parallel of the main thread, you cannot exactly achieve multi-threading using workers: you cannot modify the UI from a worker.
You can maybe create your grid as a string in a worker and when the worker finish, append it where you want.
If you do all the building of the Database in a setTimeout, the rest of the page should be responsive.
You can construct the html elements in that function, and when it is ready, attach it to the DOM. You will also have to call functions or send events to update the display of the progress bar.
Edit after comment:
This will run in background and won't affect responsiveness of the page:
window.setTimeout(function() {buildDataTable(db_table, container_id)}, 0);
You already update your progressbar from your function, so this should do it.
However, you might want to decouple the code generating the datatable from the code updating the progressbar.
So it appears the only clean way to do this in my application is to process the json on the server and build the html there. Then return the html to the browser via $.post()
The progress bar will be lost. however I can use a infinite loading gif...

Categories

Resources