Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a URL as a GET parameter in Javascript

Tags:

javascript

url

I am trying to make a bookmarklet that uses the user's current URL, kind of like the tinyURL bookmarklet that uses this javascript code

javascript:void(location.href='http://tinyurl.com/create.php?url='+location.href)

So I copied that same thing and made

javascript:void(location.href='http://mywebsite.com/create.php?url='+location.href)

Then I use:

$url=$_GET['url']; 

to retrieve it. The problem is, if I am on a url that already has some get style info in the url, it messes everything up.

Example, If I am on:

http://www.google.ca/webhp?um=1&hl=en&safe=off

The '_GET' code sets $url to be

http://www.google.ca/webhp?um=1

So I think the info in google URL is messing up all of my URL parsing, I imagine I am doing something very incorrectly or someone has a very elegant solution for this. What should I do? please help

like image 659
MikeD Avatar asked Aug 22 '10 04:08

MikeD


People also ask

Can I pass URL as query parameter?

Yes, that's what you should be doing. encodeURIComponent is the correct way to encode a text value for putting in part of a query string. but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter. Then the server is very broken indeed.

How do you give a URL parameter?

To identify a URL parameter, refer to the portion of the URL that comes after a question mark (?). URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).

What is get parameter in URL?

GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.


1 Answers

URL has a specified format. That part after ?, or to be more exactly between ? and # if exists, is called query string. It contains a list of key-value pairs - a variable name, = character and the value. Variables are separated by &:

key1=value1&key2=value2&key3=value3&key4=value4

You should escape location.href as it can contains some special characters like ?, & or #.

To escape string in JavaScript use encodeURIComponent() function like so:

location.href = "http://tinyurl.com/create.php?url=" + encodeURIComponent(location.href)

It will replace characters like & into %26. That sequence of characters isn't treated as a variable separator so it will be attached as a variable's value.

like image 170
Crozin Avatar answered Nov 15 '22 17:11

Crozin