Parameter of an URL within another URL - javascript

This is a simple to understand question, I will explain step by step as to make everything clear.
I am using the Google Feed API to load an RSS file into my JavaScript application.
I have a setting to bypass the Google cache, if needed, and I do this by appending a random number at the end of the RSS file link that I send to the Google Feed API.
For example, let's say this is a link to an RSS:
http://example.com/feed.xml
To bypass the cache, I append a random number at the end as a parameter:
http://example.com/feed.xml?0.12345
The whole url to the Google Feed API would look like this, where "q" is the above link:
https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=http://example.com/feed.xml?0.12345
This bypasses the cache and works well in most cases but there is a problem when the RSS link that I want to use already has parameters. For example, like this:
http://example.com/feed?type=rss
Appending the number at the end like before would give an error and the RSS file would not be returned:
http://example.com/feed?type=rss?0.12345 // ERROR
I have tried using "&" to attach the random number, as so:
http://example.com/feed?type=rss&0.12345
This no longer gives an error and the RSS file is correctly returned. But if I use the above in the Google Feed API url, it no longer bypasses the cache:
https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=http://example.com/feed.xml&0.1234
This is because "0.1234" is considered a parameter of the whole url and not a parameter of the "q" url. Therefore "q" remains only as "http://example.com/feed.xml", it is not unique so the cached version is loaded.
Is there a way to make the number parameter be a part of the "q" url and not a part of the whole url?

You need to use encodeURIComponent like this:
var url = 'http://example.com/feed.xml&0.1234';
document.getElementById('results').innerHTML = 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=' + encodeURIComponent(url);
<pre id="results"></pre>
You are escaping the special characters that would have been treated as part of the url otherwise.
To append or create a queryString:
var url = 'http://example.com/feed.xml';
var randomParameter = '0.1234';
var queryString = url.indexOf('?') > - 1;
if(queryString){
url = url + '&' + randomParameter;
} else {
url = url + '?' + randomParameter;
}
//url needs to be escaped with encodeURIComponent;

You need to use encodeURIComponent to do this.
encodeURIComponent('http://example.com/feed.xml&0.1234')
will result in
http%3A%2F%2Fexample.com%2Ffeed.xml%260.1234
and when appended to the end result you'll get
https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=http%3A%2F%2Fexample.com%2Ffeed.xml%260.1234

Related

Encoding json data for a mailto link

How do I properly encode a mailto link with JSON data in the query parameters so that the link works as expected when some of the JSON data possibly includes spaces?
Here is a simple example:
var data = {
"Test": "Property with spaces"
};
var mailTo = 'mailto:?body=http://www.google.com/?body=' + JSON.stringify(data);
document.getElementById("link").href = mailTo;
The resulting link in the email after clicking the link looks like this:
Here is a JSBin showing what I am talking about:
https://jsbin.com/vuweyemeji/1/edit?html,js,output
Edit: Adding encodeURI() or encodeURIComponent() doesn't seem to work for me. I tried adding either of those methods around the data object and when I click the mailto link the url still looks the same in outlook.
You need to use encodeURIComponent twice, because you are encoding a parameter inside another parameter.
Your link is using the mailto protocol and using a body parameter which content should be encoded. But, inside that content you are entering a URL which has parameters, so, this parameters should be encoded also.
Try this:
var data = {"Test": "Property with spaces"};
var mailTo = 'mailto:?body=' + encodeURIComponent('http://www.google.com/?body=' + encodeURIComponent(JSON.stringify(data)));
document.getElementById("link").href = mailTo;
<a id='link'>anchor</a>

JQuery encodeURIComponent page not found error

I'm trying to encode my uri by using encodeURIComponent function. Here is my code.
//res[0].CLIENT_ID=10 and id=res[0].CLIENT_ID
var url = "new_quotation.php?clientid="+res[0].CLIENT_ID+"&quoteid="+id;
var encodedurl = encodeURIComponent(url);
$('#edit').attr("href", encodedurl);
It successfully encodes the uri, but when the page redirects it shows error as
The requested URL /Quotation/new_quotation.php?clientid=10&quoteid=0000000014 was not found on this server.
I saw the url. It seems like
http://localhost/Quotation/new_quotation.php%3Fclientid%3D10%26quoteid%3D0000000014
So, the uri is encoded but why not the page is redirected? Do I need to use any other function to redirect? Or is there any error in my code?
You should only be encoding the values, not the entire url.
var url = "new_quotation.php?clientid="+encodeURIComponent(res[0].CLIENT_ID)+"&quoteid="+encodeURIComponent(id);
$('#edit').attr("href", url);
Since you are using jQuery, you can also use param()
Each and every parameter in the URL must be applied encodeURIComponent (if the parameter consists of special characters)
Example :
var enc =param1+'/'+encodeURIComponent(param2)+'/'+encodeURIComponent(param3);
param2, param3 - here are expected to have special chars

Iteratively obtaining different pages of a query using python

I am trying to parse a sequence of html pages using python, I am having trouble grabbing the pages in iterative fashion. The link to the web page.
Milano Library
After peeking through the source, I found a function that responds to the click event on button element for the next page.
function SaltaAPagina() {
var CalcPag = VAIAPAGINA.value;
if (CalcPag > 0) {
CalcPag=CalcPag;
}
else {
CalcPag="1";
}
document.location = "/OPACMI01/cat/SDW?W=CODICE_BIBLIO+%3D+%27LO1+01%27+AND+EDITORE+PH+WORDS+%27sonzogno%27+AND+DATA_PUBBLICAZIONE+%3C+1943+ORDER+BY+ORDINAMENTO/Ascend&M=" + CalcPag + "&R=Y";
}
I know that I can encode parameters using pythons urllib2 module using the urlencode method. But I am not sure what I should be including as a parameter
lomba_link='http://www.biblioteche.regione.lombardia.it/OPACMI01/cat/SDW?W%3DCODICE_BIBLIO+%3D+%27LO1+01%27+AND+EDITORE+PH+WORDS+%27sonzogno%27+AND+DATA_PUBBLICAZIONE+%3C+1943+ORDER+BY+ORDINAMENTO/Ascend%26M%3D1%26R%3DY'
params = urllib.urlencode([('CalcPag',4)])
# this has not worked.
req = urllib2.Request(lomba_link)
print req
response = urllib2.urlopen(req,params)
html_doc = response.read()
What am I missing here?
Thanks
The javascript function you posted is passing several parameters to the target page:
document.location = "/OPACMI01/cat/SDW" + // This is the path of the page
"?W=CODICE_BIBLIO+%3D+%27LO1+01%27+AND+EDITORE+PH+WORDS+%27sonzogno%27+AND+DATA_PUBBLICAZIONE+%3C+1943+ORDER+BY+ORDINAMENTO/Ascend" + // The first parameter
"&M=" + CalcPag + // The second parameter
"&R=Y"; // The third parameter
In your code, you've encoded all of the & and = symbols in the URL, so you're passing a single, long parameter with no value - changing those symbols back to what they were in the javascript function should do the trick.
lomba_link='http://www.biblioteche.regione.lombardia.it/OPACMI01/cat/SDW'
params = urllib.urlencode([
('W', 'CODICE_BIBLIO+%3D+%27LO1+01%27+AND+EDITORE+PH+WORDS+%27sonzogno%27+AND+DATA_PUBBLICAZIONE+%3C+1943+ORDER+BY+ORDINAMENTO/Ascend'),
('M', 4),
('R', 'Y')
])
It's much easier to work with the brilliant requests library, rather than the urllib2 library...
In regards to urllib2.urlopen the params is for POST requests. Unfortunately you need to append the query string to the url to make a GET request.
eg:
req = urllib2.urlopen(req + '?' + params)
With requests, this would be much simpler:
page = requests.get(some_url, params={'CalcPag': '4'})

Extracting part of current page's URL in javascript

In ASP.NET MVC 3 site, I open the following uri
http://myserver/incidents/supercompany/register
That page needs to make use of ajax JSON retrieval mechanism with the help of jQuery:
$.getJSON('/Incidents/[[COMPANY NAME GOES HERE]]/SearchPeople/' + request.term, function (data)
I am new to javascript. How can I obtain supercompany part of my current url to build the
/Incidents/supercompany/SearchPeople/ string?
Assuming your URLs follow a logical structure, you can do this
var URLparts = window.location.toString().substr(7).split('/');
And you can now access URLparts[1] to get the company name. Obviously, you need to be able to know that that will ALWAYS be there, but it's a solution if you can guarantee that (eg. with htaccess).

Javascript - Check for Hash, Ignore Analytics Code following

We are adding a video to the home page of a site, and want to be able to automatically pop up the video (in a lightbox-style container) whenever the #video tag is present in the URL:
http://www.domain.com#video
The video needs to pop up if a link is clicked internally on the site (ie: <a href="#video">) and also if the hash is present in the URL on page load.
Easy enough to check for the hash in the URL using window.location.hash or when a link with the hash is clicked and fire the associated javascript function. That's working as expected without any issues.
However as this URL will be sent out in emails with Google Analytics code automatically added, the analytics code is appended to the end of the URL:
http://www.domain.com#video?utm_source=...
Because the analytics code will change with each email campaign, I can't do a simple Javascript replace() to ignore the analytics code.
How do I go about checking whether the hash is present in the URL, but ignore anything after a ? if present?
Isn't the proper form of a URL to have the hash at the end after the query parameters? Then, the location.hash variable will work properly and you won't need special code. Your URL should look like this and then you can just directly use location.hash which will be #video:
http://www.domain.com?utm_source=xxx#video
I don't advise this as the solution (I think you ought to get the URLs fixed to be legal), but you can use this code to parse the hash value out of the URL even if it's in the illegal position:
var matches = window.location.href.match(/#(.*?)(\?|$)/);
if (matches) {
var hash = matches[1];
}
This code extracts from the "#" to either end of string or "?" whichever comes first. You can see it run on a bunch of test URLs here: http://jsfiddle.net/jfriend00/HuqL7/.
location.hash.match(/[^?]*/)
Assuming the hash is always first, that should do it.
(This is a literal answer to your question, but there is a huge caveate) Technically, you can just test:
var h = window.location.hash;
var ind = h.indexOf( '?' );
var test = ind <0?h:h.substr(0, ind)
If you want Google Analytics to work, you may have problems #. The rule is that everything after a # is not sent to the server, which means that your Analytics may go out the window. You need to make sure that your hash is added after all of the Google stuff. If it is, then you won't need to worry about testing anything.

Categories

Resources