Why I get some numbers added to a String variable in Javascript? - 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!

Related

Finding out generalize method to get site name from it's website using Jquery

I'm trying to get any site's name(just a domain name without any sub domain name) to use in my chrome extension using JQuery. I'm able to find it in most of the cases. but i'm failing in few corner cases. Here is what i have done till now.
host_url = window.location.hostname;
This gives me only host name stripping page url, slug or params
https://ap2.salesforce.com/_ui/core/chatter/ui/ChatterPage ->
ap2.salesforce.com
http://go.sap.com/support.html -> go.sap.com
http://www.beaf.com/ -> beaf.com
http://www.digitalclicks.co.uk -> digitalclicks.co.uk
but how can I get to only domain name, because to remove sub-domain i can get split it and get the 2nd element which will give me salesforce, sap, beaf
if (full_domain.split(".").length > 2){
domain_name = full_domain.split(".")[1]; // handle the subdomain ie. http://go.sap.com
}else{
domain_name = full_domain.split(".")[0]; //for no subdomain www.beaf.com
}
But I'm failing for digitalclicks.co.uk,because here domain name is first. I have to find a generalize approach to solve this.
And how can I do this for all Top Level Domains??
Extract domain name from any url.
http://www.domain-name.co.uk/sub1/sub2/...
This is how it works:
step: it gets rid of http(s)://
step: it gets rid of everything behind "/"
creats an array splitted by "."
cuts the length of the array to 3 to get rid of "uk" in ".co.uk" f.e.
reverse the array because the domainname has to be [1] then. You have to do this, because the url could be like domainname.com(without subdomain)
edit:
In line 1 we need to add this + "/" in case there is no slash in the url.But we need a slash in the next step to get the substring.
function getDomainName(url) {
var _x = url.replace(/\w+:\s?\/\//.exec(url), "") + "/";
var __x = _x.substring(0, _x.indexOf("/"));
var __xRev = __x.split(".");
if (__xRev.length > 3) {
__xRev.pop();
}
__xRev.reverse();
return __xRev[1]; // <-- __xRev[1] is the domainname
}
document.write(getDomainName(prompt("please enter url")));

Javascript & doesn't append next parameter value pair

I am trying to append multiple parameter value pairs to a url for an ajax request. I know that this is supposed to be done using & instead of &. Why then, does the first function work and the second one fails?
function accountByName(firstName, lastName, resultRegion) {
var baseAddress = "Bank";
var data = "firstName=" + getValue(firstName) + "&lastName=" + getValue(lastName);
var address = baseAddress + "?" + data;
ajaxResult(address, resultRegion);
}
function accountByName(firstName, lastName, resultRegion) {
var baseAddress = "Bank";
var data = "firstName=" + getValue(firstName) + "&lastName=" + getValue(lastName);
var address = baseAddress + "?" + data;
ajaxResult(address, resultRegion);
}
When I do print statements in the serverside java code the firstName variable prints fine, but the lastName variable always comes back null when I use & Both variables print fine when I just use &, but I know this is not correct XML.
So here's what your instructor meant:
In an (X)HTML page if you have something like:
Link
You should use (even though it really doesn't make a difference except to the validator)
Link
That is the ONLY time you should use an & in a query string.
You are incorrect: you are not supposed to use & as the parameter separator in a URL. The first function constructs the URL:
Bank?firstName=foo&lastName=bar
The second:
Bank?firstName=foo&lastName=bar
The 1st URL has two parameters: firstName and lastName with the values foo and bar.
The 2nd URL has two parameters: firstName and amp;lastName with the values foo and bar. (Note: I believe the second parameter name is invalid and am not sure how it'd be parsed in Java; it may be library/server dependent)
Your Java code fails printing the lastName parameter in the second case because in that case it is not set.
Your confusion seems to stem from a misunderstanding of the URL format. The URL format is unrelated to XML or HTML. It is completely separate from the two. & is an XML/HTML entity. Were the URL some form of XML, you would be correct. However, as it is not one should not expect it to follow the rules and standards of XML.
You're creating a URL, not some XML content. You have to think about what system is going to be paying attention. An XML/HTML parser is never going to look at that URL you're creating. The server, however, will certainly be interested in interpreting the URL as a URL. The XML entity syntax & is completely alien to something parsing a URL.

Passing Parameters to a Batch File from Javascript Inside Hyperion Interactive Reporting Studio

Inside of Hyperion Reporting Studio I have a document level script where I wish to call a batch file and pass arguments to the batch file.
Here is the code I have:
var Path = "W:\\directory\\Reference_Files\\scripts\\vbs\\SendEmail.bat"
var Email = "my.email#xxx.com"
var Subject = "My Subject"
var Body = "My Body"
var Attach = "W:\Maughan.xls"
Application.Shell(Path + " " + Email + " " + Subject + " " + Body + " " + Attach)
This code does not open the file, but gives the error message The filename, directory name, or volume label syntax is incorrect.
If I pass Path by itself my bat file runs (giving me a warning because no parameters are passed) and I when I run the same code from the Shell Command, it works flawlessly.
Can anyone provide any insight into the correct syntax to pass into the Application.Shell method so that it reads my parameters and passes them to the batch file? I have been searching high and low online to no avail.
Because var Attach = "W:\Maughan.xls" should be var Attach = "W:\\Maughan.xls".
Within a string the escape character \ just escapes the next character so Attach will contain just W:Maughan.xls. To add \ you need to use \ twice.
Update:
It may have no difference in this particular case, because W:Maughan.xls means to look for Maughan.xls in the current directory on the drive W which is most likely \.
But what is definitely important are quotes around the parameters Subject and Body. In you code the constructed command is
W:\directory\Reference_Files\scripts\vbs\SendEmail.bat my.email#xxx.com My Subject My Body W:Maughan.xls
I sure that the bat file cannot distinguish between the subject and body (unless it expect exactly two words in each of them) so the right command most likely is
W:\directory\Reference_Files\scripts\vbs\SendEmail.bat my.email#xxx.com "My Subject" "My Body" W:\Maughan.xls
and you can check it by running the command above in cmd.
To construct it the parameters should be modified as follows:
var Path = "W:\\directory\\Reference_Files\\scripts\\vbs\\SendEmail.bat"
var Email = "my.email#xxx.com"
var Subject = "\"My Subject\""
var Body = "\"My Body\""
var Attach = "W:\\Maughan.xls"
(this correction was inspired by impinball's answer)
Try putting an escaped quote on either side of the variable values. Depending on where the directory is, that may make a difference. The outside quotes in strings aren't included in the string values in JavaScript. Here's an example of what I'm talking about:
var Path = "\"W:\\directory\\Reference_Files\\scripts\\vbs\\SendEmail.bat\""
instead of
var Path = "W:\\directory\\Reference_Files\\scripts\\vbs\\SendEmail.bat"

Escaping & for display in mail client (mailto link)

I have a JavaScript function like so:
var strBody = encodeURI(window.location.href);
var strSubject = encodeURI(document.title);
var mailto_link = "mailto:?subject=" + encodeURI(strSubject) + "&body=" + strBody;
This code is executed on a hyperlink's onclick event, and opens the mail client (mailto://). However, the title of the page has several & symbols, but the title is only picked up until the first &. The url is always picked up.
What is the correct JavasSript to escape the & and display it in the mail client's subject line?
var encoded_body = encodeURIComponent(window.location.href);
var encoded_subject = encodeURIComponent(document.title);
var mailto_link = "mailto:?subject=" + encoded_subject + "&body=" + encoded_body;
should do it (encodeURIComponent instead of encodeURI).
In your original code you were also incorrectly double encoding the subject (once on line 2, and then again on line 3).
I took the liberty of renaming your variables to make it clearer that they contain the encoded subject and body, as opposed to the original text.
You want encodeURIComponent not encodeURI.

Changing the Question mark in my URL

I am using joomla on this site. I have an affilate program that requires me to run the following html on my page:
Header
var bid= ####;
var site =#;
document.write('');
Footer
the following url is delivered and does not work (shows a email form)
http://www.whatshappeningnow.info/index.php/index.php?option=com_content&view=article&id=764?evtid=1626579&event=ZZ+Top
Note the "?" between "=764" and "evtid="
If I change the url to:
http://www.whatshappeningnow.info/index.php/index.php?option=com_content&view=article&id=764&evtid=1626579&event=ZZ+Top
Note:I replaced the "?" with "&"
Now the correct results do display (the css needs to be adjusted, but the tickets do display!
How do I make my url write correctly from there script that I can not change.
As one comment says, the best thing to do is get in touch with the affiliate program and let them fix this.
As a workaround, you could transform the URL that is returned by the affiliate program script. Since in a URL only one "?" is allowed, you could split the URL in substrings at "?"s and then rebuild it by only putting the "?" between the first and second substrings. Something like this:
var newUrl = "";
var urlSubs = affiliateUrl.split("?");
if (urlSubs.length === 0) {
newUrl = affiliateUrl;
//-- no "?", do your processing here...
} else {
newUrl = urlSubs[0] + "?";
var i = 1;
for (i = 1; i < urlSubs.length; i++) {
newUrl = newUrl + "&" + urlSubs[i];
}
}
NB: I have not considered any error checking!
This will work for any number of "?", and will only keep the first one.
As Pekka pointed out, the best thing is to get them to fix that bug, but in the meantime, you could do something like this assuming you can somehow access the string they return:
<script>
var str = "http://www.whatshappeningnow.info/index.php/index.php?option=com_content&view=article&id=764?evtid=1626579&event=ZZ+Top";
var newStr = str.replace(/(\?)([^\?]*)(\?)/, "$1$2&");
</script>
This only works if you know that the string will always have two question marks, one in the correct place and one where an ampersand should be. It finds the appropriate string using a regular expression and simply replaces the 2nd "?" with an ampersand.

Categories