tags:

views:

111

answers:

3

how can I append variables to an URL with javascript without navigating to the url ?

thanks

+4  A: 

You can modify window.location.hash. Anything else will cause a navigation.

Matthew Flaschen
And modifying `.hash` should cause the browser to jump (navigate, if you will) to the corresponding document position (if defined).
Tomalak
@Tomalak: therefore, if the anchor is undefined, the browser will *appear* not to have navigated anywhere, right?
Piskvor
@Piskvor: Yes, it won't even flicker. This is quite a tried and tested method to attach data to the URL. Many webapps do it. Gmail is an example.
Daniel Vassallo
@Daniel: Hm… I don't quite understand what the advantage would be. Can you give an example where this would be useful?
Tomalak
@Tomalak: One example: Since hashes are stored in bookmarks, this is one technique to save the location in AJAX web apps. If Gmail attached a querystring instead of a hash in the URL, it would cause a page refresh whenever you click on something... Probably Gmail is not a very good example, but in some applications it is quite useful.
Daniel Vassallo
@Daniel: Makes sense, thank you (I was not thinking about persistence, only about "live" functionality).
Tomalak
@Tomalak: I guess Gmail use it in order to allow users to refresh the page without being sent back to the default section (which is related to the bookmarking example).
Daniel Vassallo
A: 

I am not sure about that, but how is it with this?:

document.url + myVar + 'myString';

Though Javascript is not my language :P

faileN
+1  A: 

To append variables to the hash (as Matthew suggested), you can do the following in plain JavaScript:

window.location.hash = 'varA=some_value;varB=some_value';

This will add #varA=some_value;varB=some_value to your URL. It will not refresh the page unless the hash value is equal to an anchor name or an element id within the document.

Then to check if a hash value is present, simply do the following:

var i, variables = window.location.hash.split(';');

if (variables.length > 0) {
    // Variables present in hash
    for (i = 0; i < variables.length; i++) {
       keyValuePair = variables.split('=');
       // keyValuePair[0] would be the key (variable name)
       // keyValuePair[1] would be the value
    }
}
else {
    // No variables in the hash
}

You may also want to check out the following Stack Overflow post on issues related to the URL encoding of the hash part in different browsers:

Daniel Vassallo
I'm sure there must be a `encodeURIComponent()`/`decodeURIComponent()` calls somewhere to make that work reliably.
Tomalak
@Tomalak: Yes, good point... I'm fixing my example.
Daniel Vassallo