Reading file dynamically with javascript - javascript

I'm trying to post values from a file to a textfield on a website. These values will be updated every 5 seconds. I am able to read the values using xmlHTTPrequest, however, when I try to use setInterval to run the function again, the values don't change. It detects if the file is no longer there, but as I put it back and change values, they are the same as before. This is my code:
setInterval(getrecent, 5000);
function getrecent () {
sourcestr = "../userdata/" + sessionStorage.getItem("DoB");
var x = new XMLHttpRequest();
x.open("GET", sourcestr + "/recentdata.txt", false);
x.send();
if (x.status == 404) {
document.getElementById("babypic").src = "../../Notrunning.png";
}
else {
var myTextfile = x.responseText;
// alert(myTextfile);
document.getElementById("babypic").src = sourcestr + "/picture.jpeg" + '?rand=' + Math.random();
var split = myTextFile.split(" ");
document.getElementById("pulse").value = split[0];
document.getElementById("resp").value = split[1];
}
}
I found the error but I'm not sure what to do with it. "Uncaught referenceerror, myTextFile not defined" on row 117 which is "var split = myTextFile.split(" ");
Solved: Added "meta http-equiv="cache-control" content="no-cache" " to the head to avoid caching and corrected spelling of myTextFile. Website works just fine now.

You have written the variable myTextfile in two different casing: myTextFile and myTextfile are not identical variables.
Please correct the casing and think about using an IDE that can point out such errors, it will make your life a lot easier!

Related

JSON XMLHttpRequest POST/PUT to Cherrypy application - getting no data

I want to create a Singlepage Application following REST principles. I have managed to make both GET and DELETE work, but i also need to PUT or POST data.
After failing for some time, i looked around and found some sample code here https://gist.github.com/EtienneR/2f3ab345df502bd3d13e
which, first of all, taught me that setting a request header may be helpful. With that done, however, and following the exact example, I'm still getting "None" for the field i expect to receive data on.
I may be missing something absolutely basic, and looking around some more i just can't find out what it is.
on the javascript side i've got:
update_px (path_spl, success_ppl, fail_ppl, formdata) {
this.success_p = success_ppl;
this.fail_p = fail_ppl;
var data = {};
data.firstname = "John";
data.lastname = "Snow";
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST", path_spl, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "201") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
}
and on the python side of things:
def POST(self, path_spl="NoPathError", id = None, data_opl=None):
print("POST called with path_spl " + path_spl )
if(id != None) :
print(" and id " + id)
print (data_opl)
#process data
return ' '
The method is exposed; output shows I'm receiving the correct path and ID, but data is just None even after swapping in this sample code i found.
Where am i going wrong?
I have found a way to get it to work.
1) ** was missing on the expected data - that alone didn't help, now i was getting an empty dict instead of None
2) i replaced the content type; the header is now
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
with that, i am receiving:
{'{"firstname":"John","lastname":"Snow"}': ''}
Which actually leads me into another question - how did {"firstname":"John","lastname":Snow"} become a key with an empty value during json-ification? But anyway. That's for another day to find out; i can work with what i'm getting now.

How to access to a java variable in javascript function

I have a java file called myJavaFile.java. Inside this java file, I have the following java code:
private void addUploadscript() {
//my java variable
String fn = session.getUser();
html.addElement("<script language=\"JavaScript\" type=\"text/javascript\">");
html.addElement("function ajax_post(){");
html.addElement("var hr = new XMLHttpRequest();");
html.addElement("var url = \"http://localhost:8080/bunk/inf?cmd=Dialer.opts#\";");
html.addElement("var vars = \"firstname=\"+fn;");
html.addElement("\talert(vars)");
html.addElement("hr.open(\"POST\",url,true);");
html.addElement("hr.setRequestHeader(\"Content-type\",\"application/x-www-form-urlencoded\");");
html.addElement("hr.onreadystatechange = function() {if (hr.readyState == 4 && hr.status == 200) {var return_data = \"my server is reached\";document.getElementById(status).innerHTML = return_data;} } ");
html.addElement("hr.send(vars);");
html.addElement("document.getElementById(status).innerHTML = \"processing....\";");
html.addElement("}");
html.addElement("</SCRIPT>");
}
I already tried to find my response by reading the other topics but I still can not resolve my problem.
I actually tried to do it step by step and display my variables to make sure that I wrote everything fine.
Thank you very much for your help!
I believe you want to output fn directly, something like
html.addElement("var vars = \"firstname=" + fn + "\";");
Javascript allows you to use ' or " for String(s), and you could also use String.format(String, Object...). Like,
html.addElement(String.format("var vars = 'firstname=%s';", fn));
You should change this part of your code:
html.addElement("var vars = \"firstname=\"+fn;");
For this:
html.addElement("var vars = \"firstname=\"" + fn + "\";");
Just use single qoute ' instead of \" in all your code that will make it more cleanest, and replace this part :
html.addElement("var vars = \"firstname=\"+fn;")
By :
html.addElement("var vars = 'firstname='+fn;")
Hope this helps.

loading sqlite database in javascript with sql.js

Can someone provide a simple complete example of loading an existing sqlite database not using node.js.
Assume that the sql db is sitting in same location as index.html
example:
I tried this example but "contents" is undefined. Also, I would not know how to access the data in "contents"? I could really use a complete example.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/database.sqlite', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
var db = new SQL.Database(uInt8Array);
var contents = db.exec("SELECT * FROM my_table");
// contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}]
};
xhr.send();
I know this is old, but here you go my friend. You were right there, just a bit of tweaking. I am not sure if you are using the SQL.js library from GitHub but please do as it solves a lot of the browser security issues and makes the SQL side of things much easier on the brain.
If you didn't create the source or have some UTF issues the exceptions will be thrown. I wrote this in a night so I haven't run more than a few functions but I am assuming callbacks will be required to prevent SQLite issues during async processes. This is my first time using SQLite or the SQL.js library so I just don't know yet.
IMPORTANT!
This is a LOCAL solution only, it has more blatant vulnerabilities than a high school locker room. In no way should this ever be used on anything that is exposed to the internet.
This is all declared at the top of my class, not within a function. This is purposeful as I run multiple queries and didn't want the overhead of loading/unloading the object if it got too large.
Notice the fully qualified path on the source...relative paths didn't work for me.
var xhrLocal = new XMLHttpRequest();
xhrLocal.open('GET', 'http://localhost/mp3/data/media.sqlite', true);
xhrLocal.responseType = 'arraybuffer';
var localData;
xhrLocal.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
localData = new SQL.Database(uInt8Array);
};
xhrLocal.send();
At this point you have the database loaded into an object called localData and you can query it from anywhere. Here is a query I wrote to get Genre info.
function FillGenreLists() {
var sqlSel = 'SELECT * FROM GenreData';
var data = localData.exec(sqlSel);
var output = [];
$.each(data[0].values, function(key, value)
{
output.push('<option value="'+ value[0] +'">'+ value[1] +'</option>');
});
$('#selGenres').html(output.join(''));
}
The output from the SQL call is generally an array of arrays, don't worry about changing that, just output the result of your SQL call to the console and note the return fields and values, from there just use $.each to your hearts content.
Here is another query, same premise but with the goal of creating a SQL statement to push into MS SQL server and get FreeDB data about artists that are in my local collection.
Note: This could all be done in a single call by querying my local sqlite table, generating the sql and pushing it to the MS SQL using a different conn or even better by utilizing a generic proc but let's keep it simple for now.
function PrepareMSSQLFilteredFreeDBTables(StartLetter, EndLetter, TempTableName) {
var sqlSel = "SELECT * FROM ArtistData WHERE ArtistText BETWEEN '" + StartLetter + "' AND '" + EndLetter + "' ORDER BY ArtistText";
var data = localData.exec(sqlSel);
$('.array-cols').append('SELECT * INTO ' + TempTableName + ' FROM FreeDB WHERE DARTIST IN (');
var iLen = (data[0].values.length - 1);
$.each(data[0].values, function(a, b) {
var sRes;
if (a === iLen) { sRes = "'" + b[1].replace("'", "''") + "')"; }
else { sRes = "'" + b[1].replace("'", "''") + "', "; }
$('.array-cols').append(sRes);
});
}

Simple AJAX Retrieval of data in XML file, going wrong around ".responseXML"

I've searched and searched and quadruple checked spelling and syntax and I'm stumped. I even checked the syntax on "jslint". I've placed all the code on "jsfiddle":
http://jsfiddle.net/sxtuX/
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function process() {
if (xmlHttp) {
try{
xmlHttp.open("GET", "data_people.xml", true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.send(null);
}
catch (e) {
alert ("In process function.<br/>Error in creating xmlHttp object: "+ e.toString());
}
}
}
function handleStateChange() {
if(xmlHttp.readyState==4) {
if (xmlHttp.status==200) {
try {
handleResponse();
}
catch(e) {
alert ("Trouble getting text." + e.toString());
}
}
else {
alert ("State = "+xmlHttp.readyState+" Status= " + xmlHttp.status);
}
}
}
function handleResponse() {
var xmlResponse = xmlHttp.responseXML,
root = xmlResponse.documentElement,
names = root.getElementsByTagName("name"),
ssns = root.getElementsByTagName("ssn");
alert (xmlHttp.responseText);
var stuff = "";
for(var i=0;i<names.length;i++) {
stuff = names.item(i).firstChild.data + "-" + ssns.item(i).firstChild.data + "<br/>";
}
theD = document.getElementById("theD");
theD.innerHTML = stuff;
}
The javascript works fine up until the last function "handleResponse()" which is the last function. I've placed an "alert" after all the variable declarations using "xmlHttp.responseText" just to prove to myself the file is being accessed and it does print the entire XML file in the alert window.
I tried to create the XML datafile on "jsfiddle" by following the instructions, assuming it was like the HTML file example, but I couldn't get it to work.
So my questions: Why isn't "xmlHttp.responseXML" returning anything? It's either that or something is going wrong with .documentElement. When I examine "names.length" or "ssns.length" they are both zero. Also, can I get some assistance in figuring out the proper way to code an XML file on "jdfiddle" by correcting my fibble attempt?
The way you have your javascript options in the fiddle are set up it only gets executed onLoad (which means all your functions will be defined inside an onload function - and will both not be available in the global scope nor before said function has been executed). It's a catch 22 with sprinkles on top. You'll need to set the second dropdown on the left to either No wrap - in <head> or No wrap - in <body>.
Next up - the jsfiddle example code. There's a whole bunch wrong here:
You should have been referencing Request - not Request.XML (which you just made up ;P). And you should have included the MooTools library (first dropdown on the left) - because that's where Request is from ;)
The url is case sensitive! "/echo/xml/" instead of "/echo/XML/".
The xml string needs to be have properly escaped quotes and javascript strings don't support raw line-breaks (they can be escaped too... but that's another story) - just collapse them for now.
... But you don't need that example. Just use your own code!
Just remember to use the proper test url (with POST not GET) and escape/collapse your test xml.
This is a working fiddle: http://jsfiddle.net/sxtuX/3/

Server Side Logging Of Client Side Javascript Crashes

I have a large complex web app with thousands of lines of Javascript. There is a small set of intermittent Javascript bugs that are report by users.
I think these are epiphenomena of race conditions - something has not initialised correctly and the Javascript crashes causing 'down stream' js not to run.
Is there anyway to get Javascript execution crashes to log back server side?
All the js logging libraries like Blackbird and Log4JavaScript are client-side only.
I have written a remote error logging function using window.onerror as suggested by #pimvdb
Err = {};
Err.Remoterr = {};
Err.Remoterr.onerror = function (msg, errorfileurl, lineno) {
var jsonstring, response, pageurl, cookies;
// Get some user input
response = prompt("There has been an error. " +
"It has been logged and will be investigated.",
"Put in comments (and e-mail or phone number for" +
" response.)");
// get some context of where and how the error occured
// to make debugging easier
pageurl = window.location.href;
cookies = document.cookie;
// Make the json message we are going to post
// Could use JSON.stringify() here if you are sure that
// JSON will have run when the error occurs
// http://www.JSON.org/js.html
jsonstring = "{\"set\": {\"jserr\": " +
"{\"msg\": \"" + msg + "\", " +
"\"errorfileurl\": \"" + errorfileurl + "\", " +
"\"pageurl\": \"" + pageurl + "\", " +
"\"cookies\": \"" + cookies + "\", " +
"\"lineno\": \"" + lineno + "\", " +
"\"response\": \"" + response + "\"}}}";
// Use the jquery cross-browser post
// http://api.jquery.com/jQuery.post/
// this assumes that no errors happen before jquery has initialised
$.post("?jserr", jsonstring, null, "json");
// I don't want the page to 'pretend' to work
// so I am going to return 'false' here
// Returning 'true' will clear the error in the browser
return false;
};
window.onerror = Err.Remoterr.onerror;
I deploy this between the head and body tags of the webpage.
You will want to change the JSON and the URL that you post it to depending on how you are going to log the data server side.
Take a look at https://log4sure.com (disclosure: I created it) - but it is really useful, check it out and decide for yourself. It allows you to log errors/event and also lets you create your custom log table. It also allows you to monitor your logs real-time. And the best part, its free.
You can also use bower to install it, use bower install log4sure
The set up code is really easy too:
// setup
var _logServer;
(function() {
var ls = document.createElement('script');
ls.type = 'text/javascript';
ls.async = true;
ls.src = 'https://log4sure.com/ScriptsExt/log4sure.min.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ls, s);
ls.onload = function() {
// use your token here.
_logServer = new LogServer("use-your-token-here");
};
})();
// example for logging text
_logServer.logText("your log message goes here.")
//example for logging error
divide = function(numerator, divisor) {
try {
if (parseFloat(value) && parseFloat(divisor)) {
throw new TypeError("Invalid input", "myfile.js", 12, {
value: value,
divisor: divisor
});
} else {
if (divisor == 0) {
throw new RangeError("Divide by 0", "myfile.js", 15, {
value: value,
divisor: divisor
});
}
}
} catch (e) {
_logServer.logError(e.name, e.message, e.stack);
}
}
// another use of logError in window.onerror
// must be careful with window.onerror as you might be overwriting some one else's window.onerror functionality
// also someone else can overwrite window.onerror.
window.onerror = function(msg, url, line, column, err) {
// may want to check if url belongs to your javascript file
var data = {
url: url,
line: line,
column: column,
}
_logServer.logError(err.name, err.message, err.stack, data);
};
// example for custom logs
var foo = "some variable value";
var bar = "another variable value";
var flag = "false";
var temp = "yet another variable value";
_logServer.log(foo, bar, flag, temp);

Categories

Resources