Modify Query String Without new HTTP Request - javascript

Is it possible to manipulate the query string without actually submitting a new HTTP request?
For example, I have a page that allows the user to make a bunch of changes to some configuration options. When they first go to the page it will be the following URL:
www.mysite.com/options
As they click certain elements on the page, a link here or a radio button there, the URL would be changed to something like:
www.mysite.com/options?xkj340834jadf
This way the user can copy the URL and later go to the same page and have the configuration be exactly how it was before, but I don't want to submit new requests as they click the options.
Is this something that is possible using javascript/jquery?

I don't think this is possible.
Your best solution would be to add an anchor tag to the end of the URL, which can then be read by jquery to determine a HTTP redirect.
I believe google also indexes when you use #! for this purpose.
What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

The best solution is by using hash. As Curt stated, #! is the way you tell Google that this is a webapp but if you don't need crawling, don't worry.
You can use then something like this:
var hash = location.hash; //or window.location.hash
hash = hash.replace(/^.*#!/, ''); // strip #! from the values
//do something with the values you got stored in `hash` var
If you need other things to happen, like everytime the hash changes, you do something, you can bind the 'hashchange' event.For example:
I use jQuery hashchange event by Ben Alman for that:
$(window).hashchange( function(){
var hash = location.hash;
hash = hash.replace(/^.*#!/, '');
// do something with 'hash' everytime it changes
// EXAMPLE:Set the page title based on the hash.
document.title = 'The hash is '+hash+'.';
return false; //this prevent browser from following the # after doing what you wanted
});

Related

Node js setup an Anchor [duplicate]

I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}

Redirect page and call javascript function

I need to redirect to another page onClick of submit and call a function making an ajax call. This is what I have :
$('#submitButton').click(function() {
window.location.href = "otherPage";
displayData();
});
Also, Another way I tried is to set the form fields on otherPage by using
var elem = window.document.getElementById(field);
elem.value = "new-value";
so that I could call the eventhandler of a submit button present on otherPage, but it doesn't work. Please let me know where I am wrong.
I'm not sure if there is a neat way to achieve this, but you can add a hash in your url you redirect to, then just simply check if the hash exists, execute function and remove hash.
Here are some handy URLs:
Location.Hash - information about this function and how to use it.
Removing hash from url without a page refresh - This was a bit of an issue, as window.location.href = ''; removes everything after the hash.
A hash (as Arko Elsenaar said) or a querystring parameter added to the target URL would allow you to detect what to do once there.
The hash makes it a bit easier while the querystring is cleaner if you want to pass more information.
For instance on the first page: window.location.href = "other/page.html#displayData";
On the second page:
if (window.location.hash === '#displayData') {displayData();}
Another way could be to use the HTML5 Storage API, if and only if the 2 pages are on the same domain.
1st page would do, before the redirection:
localStorage.displayData = true
And the 2nd:
if (localStorage.displayData) {displayData();}
However in this case you'll need to clean up the localStorage.displayData value when used, otherwise it will stay there forever and your second page would always find it set to true.
delete localStorage.displayData
All in all, the hash method seems best here.

Replace Values from Url using jQuery

Here i have a URL in Browser Address bar i want to replace path of Address bar using jQuery.
Some try from my side is as below
Consider url as below
http://localhost/catID/10/itemID/20
when i run
history.pushState("CatID", "Title", "21")
it change location bar as
http://localhost/catID/10/itemID/21
but i want result as
http://localhost/catID/21
how can i do this using jQuery
Query not needed. Plain js will do. Just add this code in your function and replace the string with the required arguments. Try it in the console, for an immediate effect ;D
window.location = "http://localhost/catID/10"
If you do not want to reload the page or use # for changing the url, then use window.onpopstate
Modify the URL without reloading the page
Read this article on mozilla site.

hide variables passed in URL

We've been working on a web application and we've just about got it finished up, but there's one thing that bothering us (although by no means is it going to stop production.)
When we call one of the pages (index.html), we sometimes have to pass it a variable in the URL (searchid). So we get a page like http://domain.com/index.html?searchid=string.
We'd ideally like to not show the ?searchid=string, but I'm not sure how we'd do that.
My group doesn't own the index.html page (but we are working with the group that does), so I don't know how much we'd be able to do with anything like .htaccess or similar.
I was thinking about POSTing the variable, but I don't know how to receive it with just HTML and jQuery. Another person in my group thought that after the page loaded we could remove it from the URL, but I assume we would need a page refresh which would then lose the data anyway.
I'm trying to avoid XY problem where the problem is X and I ask about Y, so what's the right way to remove the variable from the URL?
You can use the History API, but it does require a modern browser
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
More information here:
Manipulated the browser history
Your question seems to indicate that the target page is not and will not be powered by some server-side script. If that's the case, I'd suggest changing the querystring to a hash, which has the advantage of being directly editable without triggering a page-load:
http://yourdomain.com/page.html#search=value
<script type='text/javascript'>
// grab the raw "querystring"
var query = document.location.hash.substring(1);
// immediately change the hash
document.location.hash = '';
// parse it in some reasonable manner ...
var params = {};
var parts = query.split(/&/);
for (var i in parts) {
var t = part[i].split(/=/);
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
}
// and do whatever you need to with the parsed params
doSearch(params.search);
</script>
Though, it would be better to get some server-side scripting involved here.
It's possible to rewrite the URL using JavaScript's history API. History.js is a library that does this very well.
That being said, I don't think there's any need for removing the query-string from the URL, unless you're dynamically changing the contents of the page to make the current query-string irrelevant.
You could post the data, then let the server include the posted data in the page, e.g.:
echo "<script> post_data = ".json_encode($_POST)." </script>";
This works cross-browser.

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