Alert Javascript Variable outside function after reading csv - javascript

i´m reading a text-file with jquery/ajax and convert it via the jquery/csv plugin.
This is my code:
var gotData;
function read() {
$.get('text.txt', function(data) {
var options = {"separator" : ";"};
gotData = $.csv.toArrays(data, options);
alert(gotData); //1
}, 'text');
alert(gotData); //2
}
Why is the data shown in alert 1 but not in alert 2? As I know the definition of the variable is global and should be shown, am I right?
This leads to a even bigger problem because I want to access that data from my html-page (the .js is another file). So basically i want to get the variable which holds the data from my txt-file outside this function.
Hope anyone can help. For further information please comment.
Thank you in Advance.
Edit: The market duplicate doesn´t help me with my next problem, that I want to use that data in another .html-file to show it on my website.

Related

Getting Values out of Websocket Functions

I am working on a project which needs to get communication from C++ code to JavaScript on a webserver. Currently, I have data sending properly and it's being received but the issue is that I cant use the data outside of the inner(onmessage) function. This still works fine to overwrite elements of the webpage, but the charts I'm trying to build cant get the live data. If I put the code for the chart inside the inner function the entire program freezes and I can't get the variable out of the function for me to use it in the parent either. Right now, I just want to get the data out of the inner function so I can use it. So, is there any way for me to pull that data out of the inner function and use it in the parent function?
Here is my code:
{
var x;
var ws = new WebSocket('ws://localhost:10011/');
ws.onmessage = function(event)
{
x = event.data;
var testing = document.getElementById('InnerFunctionOutput');
testing.innerHTML = "Run Time: " + x;
}
var testing = document.getElementById('ParentFunctionOutput');
testing.innerHTML = "Run Time: " + x;
}
When I run this code the output from the inner function is the constant stream of data and the output from the parent is a constant 1. If anyone could help me find a solution, it would be greatly appreciated.
One alternative solution is to put the functions for the charts inside the websocket function. That way, I wouldn't have to get data out of the function. however, this solution has its own set of problems. I will put a link below to a thread where I ask about this alternate solution if you are interested in that part.
Plotly and Websockets
Any help would be greatly appreciated.
Thanks,
Luke
I found a solution to the problem. To get the data out of the websocket function I overwrote a text element on the page and simply made that element invisible. After that, just read the text element in order to get it into the rest of the code. However, there could be a better way of doing this so please let me knw if there is.
Also, there is one issue I ran into with this solution. When I originally tried this with normal formatting document.getElementById('some id').innerHTML = some data; it didn't work. But when with adding "window" to the beginning window.document.getElementById('some id').innerHTML = some data; it just worked.

Changing Javascript within an HTML document to an external Javascript file

This Javascript Function..
function ClearTotals() {
document.getElementById("total1").value = "";
document.getElementById("total2").value = "";
}
sets resets the values in two form fields. However when I move this function, unchanged, to an external Javascript and reference it in the HTML page as below:
<script src="http://xxxxxxx.org/pkjs/js1.js/"></script>
it doesn't work.
Do I need to pass some reference to the document which is used in the function, or is there some other reason why this doesn't work. Thanks
The problem is js1.js - as the error message made clear ! For some reason only the first function was being read even though I can see no problems with the structure of the file. If I delete all the other functions, and test the function by typing the url in the browser, I see the javascript code for ClearTotals().
And when I submit the HTML form, the field values clear as they should. That's really good - there are no issues with putting internal js code into an external file. Thanks again to everyone for their input and apologies that the problem seems down to me !

How to retrieve data from spreadsheet for chart google script. (Using HTML Service)

Hey good morning/afternoon/evening depending where you guys are at!
Just have a quick question for you guys. I've been stuck on this for a bit, and I've tried looking around, but i can't seem to find the answer for this specific issue.
So I'm in the process of trying to create a column chart using google scripts with the html service (since they UIApp service is depreciated now). I'm trying to retrieve the data from a spreadsheet have already created. But when i use this code, the page comes up blank as if there is some error in the background.
var sheet = SpreadsheetApp.openById("1gdRB6FFV426bAj95C0xJlqSucnnX0Z5ATVQdC2");
So here are some specifics:
1) I put this line in my Index.html file within a function I have called
drawChart();
2) I do have them wrapped in this tag.
<script type="text/javascript">
3) I know that this line of code is the cause of the issue because as soon as i comment it out my temp graph with temp data pops up, and page runs fine. But as soon as uncommented it blanks out the whole page.
Any ideas?
I'm wondering if I have to actually place this line of code within the "Code.gs" file, then some how transfer the data from Code.gs to my Index.html file. If that's the case can anyone point me in the direction to where I can follow the direction on how to do it?
Thank you guys in advance.
Sincerely,
Sicariuxs
You must use a withSuccessHandler(functionNameToReceiveData).
<script>
function getData() {
google.script.run
.withSuccessHandler(functionNameToReceiveData)
getData();
};
function functionNameToReceiveData(theDateReceivedHere) {
Logger.log('theDateReceivedHere: ' + theDateReceivedHere;
};
</script>
You can't use: var data = google.script.run.getData(); You must use a withSuccessHandler(functionNameToReceiveData).
#Sandy Good
Hey man I want to thank you for all your help. you're answer was actually great. But there was an additional mistake on top of the ones that you corrected me on. In my actual spreadsheet I had it as a "Date" value. But the format was not matching the data type in my "dataTable". It's working now though. I made all the changes you told me, but in addition I changed the value type from "Date" to "Text". Then in my for loop I wrote a "new Date()" function using the text as the format, and that worked here is some screenshots to show my end result.
link
link

Assigning json to variable

Ok, some explanation. Even though I don't think it has anything to do with the problem itself. I have a small django project that maps some data using leaflet. On a mouseover some ajax functionality is added, using the dajax(which is a "lightweight library to implement AJAX inside django projects") framework. The call itself looks like this:
dajax.add_data(simplejson.dumps(series), 'my_test_flot')
My js function receives json data which looks like this (using alert)
[{"color": "#dddd00",
"data": [[-0.5, -20.5]],
"label": "Tweede Zandlaag"}]
The object has more data to it but the problem is not with the object. When I copy/paste the data directly into the function var series = [] the behaviour is as aspected. As aspected means, the graph I'm drawing with flot is actually being drawn. Otherwise the graph remains empty.
function my_test_flot(dat) {
function MyFormatter(v, xaxis) {
return " ";
}
$(function () {
alert(dat)
var series = dat; // here lies the problem, but why?
...
Can anyone help?
Ok, problem solved. Apparently you have to use JSON.parse(). How it's done is explained here.
This does not copy the data - it just makes series a reference to the same object as dat. Therefore, if you later modify the object, all users retaining references to it see the changes. This is probably what causes your trouble.

I can't seem to receive my JSON object correctly

Sorry for the badly worded title, and I would also like to apologize in advance if my explanation is lackluster. My knowledge of JavaScript and Ajax stuff isn't really that great.
Anyway, so, what I am trying to do is display a list of items using PHP, and then when an item is clicked, a popup will be displayed basically asking if the users want to add the items to the DB (it's essentially importing from one DB to another). Part of the popup is a drop down list that contains possible parents for the imported items. (So, if you are importing a project called Vista, you might place it in the parent category 'OS').
In order to make the drop down, an ajax request must be made, and the back end PHP replies with a JSON object which contains all elements that need to be included in the drop down.
So, as a test to see if the AJAX connection works, I just arbitrarily place a button on the window like so:
<div align="center" onclick="test()">TEST BUTTON </div>
and have a JS function called test:
function test(){
var url = "index.php?module=getlist";
//Code to send post request with a callback to function test2();
}
and a function test2():
function test2(data){
if (data){
alert(data.Project[0].id);
}
else {
alert("ERROR");
}
}
Note: The PHP code returns a JSON object and one of the sub-object thingies is called Project which is an associate array with fields like id and name.
The above works. The alert box shows a number that corresponds to a project id.
But, we want to have a popup that contains the list! So, we get some html like this:
<td align="center" onclick="collection('Random_Name', 'Random_Description')">Project 1</td>
Note: I am passing the values for the item Name and Description to a JS function called collection.
function collection(name, description){
test();
//Stuff that creates the popup, creates a form in the popup, and populates the form with default values(name and description).
// Following Stuff is used to make the drop down.
var tempdata = new Array(new Array());
tempdata[0]['name'] = json.Project[0].name;
tempdata[0]['value'] = json.Project[0].id;
//This function creates the Select list, it requires a name, default value, and
//a multi-dimensional array like the one defined above.
var pacolist = createSelect("collection_list",'',tempdata)
//Append the elements together and add a save button.
}
To try and get this to work, I declared a global variable called json at the top of the page. I changed the alert(data.Project[0].id); in test2() to json = data;
But, it didn't work.
I get an Uncaught TypeError: Cannot read property 'Project' of undefined error when I click to open the popup.
I changed the test2() method to be like this instead:
function test2(data){
if(data){
return data
}
else{
//Code from the original test() function to send post request to PHP with
//a callback to test2.
}
and in the collection() function, I added this: var json = test2,(No global json) but that did not work either.
Sorry for the long winded question, but basically, I open a function, the function needs to call another function that sends a post request and the data received by the request needs to be used by the original function. How do I do this?
I think this is just a time issue. As in the request takes a while, and in the mean time, the original function has already moved on.
EDIT: Found a solution. I think it was a timing issue. In order to fix it. I made the page html call a function that stored the name and description as global variables. This function then made the post request with a callback to a different function. This different function then used the data (the JSON object) it received and passed it along with the global name and description to the collection() function mentioned earlier.
You have to parse the data before you use it.
//For IE6/IE7
var data = eval('(' + json + ')');
//For IE8+/Chrome/Firefox...
var data = JSON.parse(json);

Categories