I have existing product filters on my side bar, although I'm trying to have functional links that can update or add to the filters on the products.
snippet of current page
Currently I have the links with < a href="?filter_caster-type=swivel" > although when using that link it removes the current queries. Is there an easy way to have a link that updates or adds to the current queries?
If you are able to use URLSearchParams:
// assumes the URL already contains a query string, better checking will be needed if this isn't always the case
var paramsFromURL = new URLSearchParams(document.location.search.substring(1));
paramsFromURL.set("WhateverYouNeedToAdd", "TheValueYouWant")
// gives something like http://example.com/path/?ExistingThing=foo&WhateverYouNeedToAdd=TheValueYouWant
var updatedURL = document.location.origin + document.location.pathname + "?" + URLSearchParams.toString();
To add the query into your current URL, you can doing by a javascript function, something like this:
$(function(){
$('a').on('click', function(e){
e.preventDefault();
window.location.replace(window.location.href + $(this).attr('href'));
});
});
This function take your current URL and append the filter that you have in your a tag and then reload.
Related
I have a problem. i have a website am working on. I have created a php script to fetch all the receipts id from the data base using pagination, and all works fine. But the problem is every receipt id, i have added a link so as when clicked a specified results will be displayed without loading the page.
The links are like :
G145252 G785965 and when each link is clicked will show http://test.com/?go=any#G145252
When clicked the page will not reload.
So what i need help with is how can i get G145252 from the url after when the link is clicked using javascript and print it using html?
i need to pass the value to the process.php as a $GET value so the i can load the receipt detail of the clicked id with out reloading the page.
Please note: there are a lot of get values before the #value i need to get out of the url address.
You should not be using the fragment identifier section of the URI for server side related tasks. This section is intended for client-side manipulation only. More info here.
You can use some other means such as query parameters to access this data.
For example, turn this:
http://test.com/enter code here?go=any#G145252
Into this:
http://test.com?go=any&hash=G145252
Then:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
console.log(getQueryVariable("go")); // any
console.log(getQueryVariable("hash")); // G145252
NOTE: I know this is not the exact answer to your actual problem, but the question itself is presenting a bad practice scenario, thus my suggestion.
Credits for the getQueryVariable function goes to CSS Tricks: https://css-tricks.com/snippets/javascript/get-url-variables/?test=3&test2=5
Let's assume you're using jQuery.
Change all your links so that they have a common class name, lets say 'hashClick' e.g
My Link
To get the hash part when clicked, add a click event handler for those links
$('.hashClick').click( function(event) {
event.preventDefault();
var url = $(this).attr('href');
var hash = url.substring(url.indexOf('#')+1);
alert("You clicked " + hash);
// or at this point you can do an AJAX call
// or GET request to process.php with hash as one of the parameters
})
suppose this is the link
http://test.com/?go=any#G145252
to get the hash value
window.location.hash
which will return you #G145252
and
window.location.hash.substring(1) will return you "G145252"
Background: I have little knowledge of javascript, only html and css.
My Problem: I have a dynamic table on my webpage (WPDataTables) that includes a global search and then column specific search. My users can type into these searches and the content will dynamically update. My problem is the URL does not update to include search parameters so we cannot copy and send URL's to other people that include specific search results.
WpDataTables currently has the following keys to pre filter the table:
Global: ?wdt_search=filtervalue
Column: ?wdt_column_filter[ColumnName]=filtervalue
This is great but my users aren't savvy enough to create their own URL strings and there are a large number of possible filters so pre-creating each one is not an option.
Currently: I am close to getting a solution, I think, with the following:
<body>
<button onclick="updateURL();">Update</button>
<script type="text/javascript">
function updateURL() {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?para=hello';
window.history.pushState({path:newurl},'',newurl);
}
}
</script>
</body>
Ideally, with this the user will simply click the Update button to update the URL with the current search parameters. The problem is ?para=hello is just a hard coded parameter and I can't figure out how to get it to be dynamic and change with the users searching/filtering.
My website: http://imsched.com/sailings
The query string can't be updated without reloading the page. If you want to track those updates in the url so they are shareable, and still have them affect your filters you could use the hash instead. The hash can be easily read and you can update it without reloading the page.
// to read
window.location.hash
// to update
window.location.hash = 'param=value¶m=value'
If you had a url like this http://url.com#1=one&2=two&3=three, you could do the following:
var filters = window.location.hash.split('&')
// filters now = ['1=one', '2=two', '3=three']
// so you can make easy use of those
Update
If you need to update the query string and don't mind that it reloads the page each time, you can manipulate it via window.location.search
// to read
window.location.search
// to update (will reload the page)
window.location.search = window.location.search + '&your_stuff=here'
A function that could build your query string from your filter fields could look like this:
function buildQuery() {
var inputs = [].slice.call(document.querySelectorAll('.js-filter'))
return inputs.reduce(function(str, el, i) {
return str + (i > 0 ? '&' : '') + el.name + '=' + el.value
}, '')
}
Example fiddle here
You can try use HTML5 History Manipulation:
https://css-tricks.com/using-the-html5-history-api/
It's more commom with AngularJS, etc...
Sorry, the above solution didn't work for me you can try this:
window.location.pathname.replace(/[^a-zA-Z ]/, "");
I am working on a feature for my site that allows the user to use the back button and not have to load more database results.
I start by loading 16 results, and then there is a load more button which loads the next 16. In the ajax success i change the href of this button so the url changes to e.g. domain.com/#1 to #2.
I wrote this last night:
// First get the page URL and split it via # signs
var parts = location.href.split('#');
// now we run a check on the URL and see how many 'parts' there are
if(parts.length > 1)
{
var params = parts[0].split('?');
var mark = '?';
if(params.length > 1)
{
mark = '&';
}
location.href = parts[0] + mark + 'page=' + parts[1];
}
Which gets the URL, and redirects the user the same page but converts the fragment number to a page number. From this i then use a PHP $_GET and set the limit claus last value from that.
This works fine. But its primitive. Let for instance say i push back and the URL becomes:
www.domain.com/?page=1
If i then click to load some more data, the page url becomes:
www.domain.com/?page=1#2
If the user then visits another page and comes back then they get directed to:
www.domain.com/?page=1&page=1
Whats the best way around this? I was thinking of running a check on the URL at the same time as looking for a fragment and if the URL has a page variable i then add that variable to the fragment variable and the page URL becomes ?page=THE SUM NUMBER
Any help on modifying the snippet i posted above to check the URL for a page value and then add the two together before the redirection?
Thanks!
You need to use location.search to get the query string on a URL:
var queryParameters = location.search.split('&');
Then you can loop through the queryParameters and check if page is set:
var pageNumber = 0;
for(var i = 0; i < queryParameters.length; i++)
{
var keyvaluePair = queryParameters[i].split('=');
if(keyvaluePair[0] == 'page')
{
pageNumber = keyvaluePair[1];
break;
}
}
Please see the documentation on the MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
You might also find this example useful for returning one value:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location#Example_.236.3A_Get_the_value_of_a_single_window.location.search_key.3A
If you want to get the information after the #, you need to use location.hash. The MDN documentation I linked also has information on location.hash.
Is it possible to append a string to url using the body? Something similar to the JSFiddle below.
http://jsfiddle.net/qXs77/
hi
I want to append this query to the url: ?q1=iPodTouch&x=79&y=20
When the user clicks the link they will be taken to the next page with the attached string above.
Updated :
No need to pass it on another function ,
Use like this:
Navigate
If you wanted to utilize jQuery more you could try this approach.
$('a[data-page]').on('click', function(e){
e.preventDefault();
var page = $(this).data('page');
location.href += ( location.search.length ? '&' : '?' ) + 'page=' + page;
});
and have the HTML look like:
Page 2
I have a hard coded URL like so:
https://bupacouk.bwa.local.internal.bupa.co.uk/cash-plan-quote/quoteAction.do?getBenefitLevelDetails=getBenefitLevelDetails&productPolicyId=7841#a1
When Javascript is enabled i don't want the hash value on the end so how do i remove it?
When Javascript is disabled it needs to be present.
Thanks.
EDIT
Here is the AJAX jQuery that i am using. So i am pasisng the hard coded URL to the same page on the server and retrieving a table from it:
// Find href of current tab
var $tabValue = $(this).attr('href');
// AJAX new table in
$.ajax({
type: "GET",
cache: false,
url: $(this).attr('href'),
success: function(data){
// Find benefit wrap
$(data).find('.benefitWrap').each(function(){
// get the contents
var $benefitWrap = $(this).html();
// replace contents on page
$('.benefitWrap').replaceWith($('<div class="benefitWrap">' + $benefitWrap + '</div>'));
});
}
});
original
It depends on what the hash value does. If it just moves the document down to #a1, you just need to set scrollTop to 0 after document has been loaded probably.
edit
looking on other stackoverflow questions,
parent.location.hash = ''
should do it, but maybe reloads the page (you have to test it)
Other than that, I advice you to handle it during/before your AJAX calls - i.e.
if (hash != 'a1'){ doAjax(); } //pseudocode obviously.
edit 2 with code based on posted code
Or, if you just need to call AJAX with url without hash, you can delete it in string, that calls the jQuery, no?
var $tabValue = $(this).attr('href');
var $withoutHash = $tabValue.substr(0,$tabValue.indexOf('#'));
we basically get a's href before first #
A simple window.location.hash="" will do it.
This might be helpful to someone asking the same question, how to pull the data following a # in a href.
this.hash.slice(1);
This will give #123 as 123.
Edit: I should probably note, if you're going to be calculating numbers from this data, best to use parseInt(this.hash.slice(1)); or else you'll get funky results.
This works for me. I have added a ! to prevent the page from scrolling up.
window.location.hash="!";