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.
Related
Long story short, I got an idea of how to 'give each user their own page'. On instagram, a user's page would be https:instagram.com/{username} and on my project, its basically the same after passing the username as a url param as well as putting the rest of the data in the query so I can then call it. When I click each user's page, I get redirected to the "user's page" and I get an error that says "BadRequestError: Bad Request".
This is what happens when the user is clicked(the params are added to the url)
function userClicked() {
var i = 0;
const queryString = window.location.href;
console.log(queryString.concat('/', username));
window.location = queryString.concat('/', 'username=', username, '%', 'name=', fln)
}
What am I doing wrong/why aren't the individual pages showing up?
In addition to the post from SoftDev:
First of all, you should replace % with an &. The reason for this is that % is used for url-encoding. %20 for example might indicate a space and %21 might indicate a exclamation mark. The symbols ? and & are used to indicate query parameters. Where the first query parameters would be led by a ? and all following query paramters by a &.
For example: https://stackoverflow.com/index.html?name=test&username=larssy1&age=99
Coming once again back to (copy/paste from SoftDev) (Take note that I did change the / to a ?.
function userClicked() {
var i = 0;
const queryString = window.location.href;
console.log(queryString.concat('/', username));
window.location = queryString.concat('?', 'username=', username, '&', 'name=', fln)
}
However, aside from that, it would be wise to look up the meaning of window.location.href. As that indicated the page currently visiting.
For example: The window.location.href of this stackoverflow topic is "https://stackoverflow.com/questions/63734257/how-do-i-load-a-page-for-each-user-after-setting-their-username-as-a-search-para".
In your code, that would result in us navigating to https://stackoverflow.com/questions/63734257/how-do-i-load-a-page-for-each-user-after-setting-their-username-as-a-search-para/username=test&name=larssy1
For all possible properties and meaning of window.location, you can refer to this w3schools page: https://www.w3schools.com/js/js_window_location.asp or this Mozilla page: https://developer.mozilla.org/en-US/docs/Web/API/Location
I'm guessing you would like to use hostname or origin.
I am not sure why you used '%' but it should be updated to '&'
function userClicked() {
var i = 0;
const queryString = window.location.href;
console.log(queryString.concat('/', username));
window.location = queryString.concat('/', 'username=', username, '&', 'name=', fln)
}
Also I would prefer the following code for simplicity
function userClicked() {
var i = 0;
window.location = `${window.location.href}/username=${username}&name=${fln}`
}
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"
I have a webpage that has a dynamic search field that will query a database as you type in the search string (much like a google search with suggestions as you type). This part works via AJAX.
In the results, there are multiple rows of data that are displayed below as data is entered into the search field. What I decided to do is create an edit link on the right side of each row (with pencil icon) that is returned by ajax so I can click to another page for editing the data. Something like this...
<a href="edit.php?id=12&search=Goodyear"><i class="fa fa-pencil" aria-
hidden="true"></i></a>
So lets say that I searched for "Goodyear" in the example search and on row 12, I click the link that takes me to another page. I was wanting to use $_GET["search"] to turn around and create a BACK link to the original AJAX page. I know how to get this far, however, I need help customizing the ajax to reload the original search (which in this example is "Goodyear") when the link is clicked back to the search page. The link on the EDIT page would look something like:
Back to Search Page
But here is the issue. When the user returns, I need the search bar prefilled and the search results listed below. In other words, I want the page to be just like it was when they left prior to going to the edit page. I want AJAX to search the search again on page load just because it visited this url /search.php?search=Goodyear Making the url in the link on the edit page is not a problem for me. But it is when it is clicked to return to original search page.
Here is the AJAX code that does all the heavy lifting on the search.php page.
<script>
$(document).ready(function () {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: { query: query },
success: function (data) {
$('#brand').html(data);
}
});
}
$('#search_text').keyup(function () {
var search = $(this).val();
if (search != '') {
load_data(search);
}
else {
load_data();
}
});
});
</script>
I know that this search happens on a keyup event and the div called #brand displays the resulting rows of data below the search bar. It actually works well just on the search alone, but leaving the page and clicking back with a url (search.php?search="goodyear") like I mentioned is not doing what I need it to.
When I try to modify it, the search results stop showing. .
I have tried to customize this code to process the url using GET variable within this code that uses POST in the AJAX but I have been been unsuccessful so far. Any ideas on what I need to do?
I found the original page I originally used to make my search page.. here it if anyone wants to look: http://www.webslesson.info/2016/03/ajax-live-data-search-using-jquery-php-mysql.html
This may not be the perfect answer but it does work pretty nicely. Although the only thing it does not do is show the text in the search field when you return to the page. If anyone know how, give the answer... but this is what I did...
I found a nice piece of code that strips out the value of the parameter in the url and then throws it into an array variable. I found it on http://www.designchemical.com/blog/index.php/jquery/8-useful-jquery-snippets-for-urls-querystrings/. Here is the code.
var vars = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
load_data(vars['search']);
search is the parameter in the url and if it says search.php?search=255 then it returns 255. So I threw that into the load_data argument value and it does the search. The only drawback so far is I haven't figured out how to make the value show in the search bar. I'll keep plugging.
UPDATE: I figured out the text in search box issue with this code:
$('input[name="search_text"]').val(vars['search']);
It put the search parameter back into the search input field like I wanted! One more note, be sure to put the above code above the load_data(vars['search']); may not matter but that is what I did to make it work!
This is what it looked like:
var vars = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
$('input[name="search_text"]').val(vars['search']);
load_data(vars['search']);
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 collecting data from a user on Server A,
I need to send that data in a URL to server B (separate buildings and companies)
On server A it is a CRM system which is pre built and I cannot just simply use PARAMETERs as I cannot HASH the PARAMETERs as the system is pre built by a third party and they would charge to allow for this.
So I have managed to build some JS that replaces certain characters from the PARAMETERs I can collect.
Here is a small snippet of what I have to make my HASH.
<script type="text/javascript">
// Collect USERID
var m = 'XX784188';
// HASH USERID
m = m.replace(/7/g, 'M');
m = m.replace(/4/g, 'S');
// Set up Object n as Location name.
var n = 'Cumbria';
// Rename Location to correct code
n = n.replace(/[Cumbria]/g, '01');
// Test Object m & n
alert(n);
alert(m);
Here is the above in a test.
Now what I cannot seem to find out is how do I insert the results into a url and redirect the user to that URL.
For example:http://google.com/?n=&m=
I can insert this line I know for the redirect:
window.location = "http://google.com/?n=&m="
I just need to know how I make that URL look like this google.com/?n=01&m=XXM8S188
Funny, I just answered the same thing 1min ago :
window.location = "http://google.com/?n="+n+"&m="+m
Your snippet code and JS Fiddle code are different.
For snippet code then you simply insert your values like,
window.location = "http://google.com/?n="+n+"&m="+m;
For JSFiddle code, then,
window.location = "http://google.com/?"+serialiseObject(obj);