reference does not exist with custom function - google script - javascript

I'm trying to call this API response using a custom function where I can change the parameters. This is my code:
function callCandles(pair, start, end) {
var response = UrlFetchApp.fetch("https://api-pub.bitfinex.com/v2/candles/trade:1D:" + "pair" + "/hist?limit=1000&start=" + "start" +"&end=" +"end" +"&sort=-1");
var fact = JSON.parse(response.getContentText()); //parse the data from the API and store it in the variable data and convert response to text format//
return fact;
}
This is what I'm typing in the spreadsheet:
=callCandles(tBTCUSD,"1577841154000","1606785154000")
But when I do it I get a "reference does not exist" error.
Thank you.

Please modify as follows and test it again.
Modified script:
function callCandles(pair, start, end) {
var response = UrlFetchApp.fetch("https://api-pub.bitfinex.com/v2/candles/trade:1D:" + pair + "/hist?limit=1000&start=" + start + "&end=" + end + "&sort=-1"); // Modified
var fact = JSON.parse(response.getContentText()); //parse the data from the API and store it in the variable data and convert response to text format//
return fact;
}
Please use pair, start and end as the variables.
I thought that the reason of your error message is due to this. And also, please modify as follows.
Modified formula:
=callCandles("tBTCUSD","1577841154000","1606785154000")
Please use "tBTCUSD" as a string enclosed by ".
Note:
For example, when pair is used as "pair", pair is the string value. By this, even when =callCandles("tBTCUSD","1577841154000","1606785154000") is used, "tBTCUSD" is not used and "pair" is used.
When =callCandles(tBTCUSD,"1577841154000","1606785154000") is used, in this case, tBTCUSD is used as the named range. By this, when there is no named range of tBTCUSD, #NAME? is returned. By this, pair of function callCandles(pair, start, end) { is #NAME?. Please be careful this.

Can you be more specific, in which line does the error occur?
Maybe the problem is that the variable you are passing the function are actually not used:
var response = UrlFetchApp.fetch("https://api-pub.bitfinex.com/v2/candles/trade:1D:" + "pair" + "/hist?limit=1000&start=" + "start" +"&end=" +"end" +"&sort=-1");
The parameter pair, start and end should be added without quotation marks. You should also use the newer syntax for some cleaner code:
var response = UrlFetchApp.fetch(`https://api-pub.bitfinex.com/v2/candles/trade:1D:${pair}/hist?limit=1000&start=${start}&end=${end} &sort=-1`);
And as #tanaike pointed out, use tBTCUSD with quotation mark like this "tBTCUSD"

Related

Change the value of javascript variable dynamically

I have javascript variable var result as following which has java variable that have JSON data like this
var result = <%=JsonData1%> ;
alert(result.toSource());
Above code similar to this code as showing on alert message
var result= [{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}];
but I need to place a single quote on JSON data
'[{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}]'
and place it in new javascript variable like this
var json_pre = result;
alert(json_pre);
but when I change my result data that placed in new json_pre variable as in this link How to add single quote in the variable in Javascript?
var json_pre = "'" +result+ "'";
alert(json_pre.toSource());
then json data shows me like this on the alert message
'[{year:(new Date(-2208058200000)), value:6694}, {year:(new Date(-2207971800000)), value:50}, {year:(new Date(-2208403800000)), value:4776}, {year:(new Date(-2208317400000)), value:29006}, {year:(new Date(-2208231000000)), value:1751}]'
As I have tried every method that given me on that link.So anyone can help me in this?
result is not JSON, but a JavaScript object.
What you need to do is to stringify your object to JSON and then add the quotes:
var result = [{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}];
var result_pre = "'" + JSON.stringify(result) + "'";
console.log(result_pre);
But it is questionable why you would even need that.
You need to understand the single quotes does not make an object a string. When you are trying to store it in a variable I guess you are making the same mistake again.
when you do this
a={"key":"value"}
b="'" + a + "'";
You get a string representation for consoles, if you want a JSON string to be stored in a variable you need to do this
var json = JSON.stringify(result);
alert(json);
You don't need quotes for that.

filtering object so that only certain links are accepted

I'm trying to filter urls I grabbed using json but the code is not working
$.each(data.next, function(z,item){
JSON.stringify(item.data.url);
var url =item.data.url;
if (url.substring(0,11)=='http://youtub'){
var x = '<p>' + url + '</p>'; //this line and the one after that is just to put it in html
$(x).appendTo("#text");
}
});
Where did I make the error? I've never used stringify before so is that it?
Have you try actually using the variable return by JSON.stringify?
var url = JSON.stringify(item.data.url);
JSON.stringify doesn't modify the argument it is given, it return a converted format
See documentation
Also I am not sure why would anyone want to convert an easy to iterate over object into a string to build a filter. If anything a well build object would make filtering a bliss.

How do I store xml as a string variable in javascript?

I trying to store a piece of xml into a string variable in javascript and in IE8 it keeps throwing an error. FireFox doesn't show the error but of course in IE8 it does. Swictching browsers isn't an option so I have to try to solve this one.
The purpose of the function is to check if the items of a list exist in an xml object or not. So if there is a better way to do that check I am open to that as well. The system we pull from has a function to convert the xml to a string. At the bottom is an output of what that retrieves. Here is the function.
function commodityExists(newCommodityCode){
var comExists = new Boolean(0);
newCommodityCode = ">" + newCommodityCode + "<"
var strXML = 'tw.local.aribaHeader.commodities.toXMLString()'; //ERROR HERE
strXML = strXML.toString();
if(strXML.indexOf(newCommodityCode,0)>0){
comExists=true;
}
return comExists;
};
Here is the output from strXML.toString(); but as you can see it is essentially xml.
var strXML = ‘<variable type="NameValuePair[]">
<item type="NameValuePair">
<name type="String"><![CDATA[No Data Found]]></name>
<value type="String"><![CDATA[95990070]]></value>
</item>
</variable>’;
I don't know what you think the code is doing, here is an explanation of what it does:
> function commodityExists(newCommodityCode){
> var comExists = new Boolean(0);
Do you really want a Boolean object? This function might return a Boolean object or primitive depending on what happens later. Consider:
var comExists = false;
.
> newCommodityCode = ">" + newCommodityCode + "<"
That overwrites whatever value was passed to newCommodityCode from the call.
> var strXML = 'tw.local.aribaHeader.commodities.toXMLString()'; //ERROR HERE
I can't see how that throws an error, it's a simple assignment of a string.
> strXML = strXML.toString();
That effectivly does nothing - it calls the toString method of a string, which will just return the same string.
> if(strXML.indexOf(newCommodityCode,0)>0){
That test will always be false, since the value of nweCommodityCode is hard coded in the function and does not exist in the (hard coded) value of strXML.
> comExists = true;
> }
> return comExists; };
The function will always return false (though the original will return a Boolean object with a value of false).
You're creating a string:
var strXML = 'tw.local.aribaHeader.commodities.toXMLString()'; //ERROR HERE
^--- ^---
then converting that string to... a string?
strXML = strXML.toString();
Where would this tw object be defined that you seem to be attempting to use? Because as your code is written now, you're not calling a .toXMLString() method on something in this tw object. You're just assigning the literal text of an object call as a string itself.
The approach I was trying to take will not work because I am dynamically populating the xml so there is no way for me to escape the characters (well there probably is somehow but clearly it is not worth it). Storing HTML or XML code in javascript variables
Instead I am moving the comparison to the server side instead of retrieving the xml and comparing on the client side and posting back the results via ajax unless someone has a better reccomendation.

HTML5 data being read as a number instead of a string?

I have the following HTML:
<tr id="row_1" data-rk="02000008" data-pk="0001I">
When I check this with firebug it shows as:
dataset DOMStringMap { rk="02000008", pk="0001I"}
pk "0001I"
rk "02000008"
I then use jQuery to read this:
var pk = $("tr[id='row_" + row + "']").data('pk')
var rk = $("tr[id='row_" + row + "']").data('rk')
However this is what the firebug debuggers shows when I check the values in my javascript. They are also the same values that are later sent to my C# code in an Ajax call.
pk shows as "0001I"
rk shows as 2000008
Can someone explain this? Both rk and pk are coded in the same way, both have one or more leading zeros but the one returns as a string and the other as a number.
Javascript autoparses so the trailing 'I' in "0001I" causes javascript to interpret it as a string
This is by design:
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.
What you have to use instead is:
var pk = $("tr[id='row_" + row + "']").attr('data-pk')
var rk = $("tr[id='row_" + row + "']").attr('data-rk')
Try:
var pk = $("tr[id='row_" + row + "']").attr('data-pk');
Since jQuery is messing up your data, you can do:
var rk = document.getElementById('row_' + row]).getAttribute('data-rk');
and you are guaranteed a string.

Why I get some numbers added to a String variable in Javascript?

I'm trying to concatenate some String variables in Javascript in order to make it contain a file path which has to be calculated to load some flash charts.
If I alert the variable it shows properly but when i invoke the method to load the chart I get an error cause the path it receives isn't the one I see on the alert and thus the one it should be. It's the same string but with some numbers added at the end preceded by an interrogation mark, like '?1297931086408' for example.
Therefore the path is the right path plus this substring which is 'unloadable'.
Thanks in advance for your help!
The problem is not on your javascript. It's on your server.
For a server, this path:
/path/to/my_file.csv
Should be equivalent to this other path:
/path/to/my_file.csv?1425432456
Inside a url, the part to the left of the question mark references the resource being requested. The part to the right are parameters.
That "random number" at the end is a parameter that prevents caching. If it wasn't there, most browsers will say "hey, I already know what is on /path/to/my_file.csv, I don't need to get it again" and will use a cached version of the data. Chances are that flashmovie.reloadData is adding that parameter itself.
Make sure that the file get downloaded if you type its address directly into the browser url bar. Then, try adding a question mark and some random numbers. If that doesn't work, then your server is being overzealous on its url validation.
The code is pretty simple:
function setDataModified(businessUnit){
var path = "https://....";//Complete path
var csvPath;
var xmlPath = path + "Monthly%20Charts/" + businessUnit + "/";
var csvPath = "";
csvPath = path + "Monthly%20Charts/";
//Take data from the form
var selectedMonth = document.getElementById("monthForm").value;
var selectedYear = document.getElementById("yearForm").value;
//Generate csv's path
csvpath += selectedYear + "/" + selectedMonth + "/Monthly_" + businessUnit + "standardChart__" + selectedMonth + "_" + selectedYear + ".csv";
//setData call
var flashMovie = document.getElementById("amcolumn1");
alert(csvPath);
flashMovie.reloadData(csvPath);//csvPath contains the path and also some numbers like '?129..'
}
When I try to load the new chart i get and error message pointing out the error and the wrong path, i.e. with the added numbers at the end.
Thanks!

Categories