Is there better way reading values form url in JavaScript - javascript

I came across old web application which has the code to read the parameters from the URL of the site. The code is full of string processing.
http://hostname.domain[port number]/application name?arg1=value1...&argN=valueN
Considering that URL parameters are always encoded it is litter difficult to rely on string processing. Also not sure if one can rely 100% on the URLEncode/Decode functions of the JavaScript.
function getURLParameters(){
if (location.search != "")
{
var x = location.search.substr(1).split(";")
for (var i=0; i<x.length; i++)
{
var y = x[i].split("=");
alert("Key '" + y[0] + "' has the content '" + y[1]+"'")
}
}
}
Now that made me think if there is any better way we can read values from URL ? OR should we go ahead and change the approach itself by sending values using POST/dumping JSON object on cliente ? Please help me with this.

I found this little query string plugin that seems to do the job
The example:
http://terenz.io/?test=yes&javascript&something=1
$.getQueryParam("test") returns "yes"
$.getQueryParam("javascript") returns ""
$.getQueryParam("something") returns "1"
$.getQueryParam("somethingelse") returns undefined

Related

Creating and populating a json object

I need to construct and populate a json object with values coming from a method.
A bit of background to this: I'm searching pdf documents with a designated keyword and if I find any match, for each match I need to save:
-the whole sentence where the match is found
-the search term (defined elsewhere: the search term is always the same, so it's really redundant here, but I might need it in the json object that's why I'm including it)
-the result (which is the index where the search term is found in a whole sentence and it should be an integer)
So, here is some code.
I have this function call inside a loop (the loops goes through the pages and then there is a second loop that goes through the text):
for(var i = 0; i < items.length; i++){
lineWithResult = searchPdf(block.str);
if(lineWithResult != null){
console.log(lineWithResult + " wordCounter is " + wordCounter);
}
}
and the function itself:
function searchPdf(toSearch){
var result = toSearch.toLowerCase().indexOf(searchTerm);
if(result >=0){//if match is found
wordCounter++;
//console.log("toSearch " + toSearch + " result is " + result + " wordCounter " + wordCounter);
return toSearch;
}
else{//if match not found
return null;
}
}
SO I need to construct a json object that at each iteration takes in the parameters discussed above:
So, what would be the best way - I'm a bit rusty with json?
I think I would start by creating an empty object like so (if that's even a valid definition):
var searchResult = {"Line" : "", "SearchTerm" : "", "Result" : ""}
If the above is right, where do I define the object and how do I fill it up with the relevant values? Bear in mind that there will be a lot of Lines, one search term and a lot of Results because the documents (a pdf) which I will use are quite big and can returns lots of matches
thanks
With saying something like that:
var searchResult = {"Line" : "", "SearchTerm" : "", "Result" : ""}
You have already defined the object. JavaScript (at this point) is prototypical, not a "class" based language. JSON in JavaScript is not much more than just a plain JavaScript object. If you want to to create multiple objects of that kind, you have various options. I recommend you to read about JS Object creational patterns.
Here is a good link.
That being said, you could do something like that:
// ... maybe inside a function
return {
line: myLineValue,
searchTerm: mySearchtermValue,
result: myResult
}
There is no need to init something with empty values; you just create the object with the curly brackets.
Hope this makes sense to you; if not, let me know in the comments, and I will try to improve my answer. :-)

Security issues with reading a JS array?

I'm building a website that will have a JS multi-dimensional array in a .js file in the scripts folder on the server. In the array will be video embed codes (Vimeo iframes) and additional strings for composers, players and piece names. There will about 1000 videos in the array.
var videos = [ ['embed code', 'composer name', 'player name', 'piece name'], ['embed code', 'composer name', 'player name', 'piece name']...];
There will be a search text box for users to do specific searches by composer, player, etc. A jQuery script will iterate through each inner array to find matches to the user's query and present them on the page. It will look basically like this:
function getArray(video) {
if (campyear === video[j]) {
var pos = video.indexOf(video[j]);
$('#searcharea').append('<td>' + video[(pos - pos)] + '</td><td><h3>Composer: ' + video[(pos -pos) + 1] + '</h3><br><h3>Player: ' + video[(pos - pos) + 2] + '</h3><br><h3>Piece: ' + video[(pos - pos) + 3] + '</h3></td>');
}
else
noResultCount++;
if (campyear === video[j] && count % 2 === 0)
$('#searcharea').append('</tr><tr>');
if (campyear === video[j])
count++;
if (i === videos.lenght && j === 4)
$('#searcharea').append('</table>');
if (noResultCount === videos.length * 5)
$('#searcharea').html("<h4>No results found for " + yearvalue + " " + buttonvalue + ". Not all camps have videos for every year.</h4>");
$('#searcharea').fadeIn(500);
} // End of getArray()
...
...
...
for (i = 0; i < videos.length; i++) {
for (j = 0; j < 5; j++) {
getArray(videos[i]);
}
}
I know there are security issues with the traditional SQL databases and PHP that need to be considered, but in this case should I be concerned about any threats to the data or website? My thought was the script can only read the data and print it so there wasn't much someone could do, but I'm not sure. The data isn't sensitive.
Thanks for your time.
The issue is that if someone can alter the file before it gets read in, they can inject any JavaScript code into it. One way to alter the file would be to hack your server, but they could also do it by taking over proxies that don't have to touch your machine at all. They they would have to somehow trick clients into going through the proxy, but you can't stop that from happening.
The easiest fix for this is to use a JSON file instead of a JavaScript file. JSON's syntax is very close to the syntax used for JS literals: as far as I can see from your example, the only changes you'd need to make to the file are to get rid of the "var videos =" at the start and swap your single-quotes for double-quotes. In code, exchange whatever works to this effect:
// Assume that getJS() grabs your JavaScript file
// and returns a String with the text of that file.
var videoCode = getJS();
eval(videoCode);
...for something that works like this:
// Assume that getJSONData() grabs your JSON
// and returns a String with the text of the file.
jsonData = getJSONData();
var videos = JSON.parse(jsonData);
Note that we're using JSON.parse (which has polyfills for old browsers) instead of eval. We do this because that puts the code through a dedicated JSON parser instead of a JavaScript one. JSON doesn't know how to deal with code, so even if an attacker tries to inject code by changing the file, the changed code won't work, because JSON won't know what to do with it. Obviously you don't want your app to just stop in the middle, but it's better than letting the attacker take over.

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.

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.

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