Getting the value of # from a url - javascript

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"

Related

How to pass a url variable into an Ajax post script to preload a form input in search field?

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']);

Parse URL and load corresponding data

I’ve successfully implemented routing and hashing with crossroadsJS and hasherJS on a SPA I’m working on. The data I’m loading from a REST API is entirely event based. This works fine for navigating through the website with click based events. However, I want to implement the ability to type in a URL (or refresh the current view) and load the data corresponding to that URL. I wrote a method like this:
// app.js
app.helpers = {
routeMagic: function (prop, clicked, type, el) {
var parser = document.createElement('a'); // setup parsing
parser.href = hasher.getURL(); // use hasher's .getURL() to find current URL
var splitURL = parser.hash.split('/')[2]; // split at second / ... example: /conditions/annual-wellness-exam => annual-wellness-exam
propArr = []; // set up array to store name property
for (var i=0, len=prop.length; i<len; i++) {
propArr.push(prop[i].name.replace(/,/g, "").replace(/\//g, "").replace(/[()]/g, "").replace(/\s+/g, "-").toLowerCase());
}
$(el).each(function () { // target li ... example ‘.returned-list li’
var val = $(this);
val.id = propArr; // append name to li id
var id = $(this).attr('id');
// this is only executing on click event, need it to execute on refresh or typing in URL
if (splitURL === id) { // find a match
console.log('match found');
clicked = val.children().attr('data-id'); // determine where to route the page to based off data-id
return false;
}
});
type(clicked); // init crossroads routing
}
};
Which would be called like so:
// routes.js
conResultsRoute = crossroads.addRoute('conditions/{name}', function () {
app.helpers.routeMagic(cache.lists.conditions, cache.justClickedCondition, api.endpoints.condition, '.returned-list li');
});
For this example, when I click on a ‘conditions’ link from a list of conditions, the expected results are returned on the following route. However, if I try to type in the same URL, I get a list back of all the data stored in the CMS rather than my filtered list like when I click through the app. I think the problem stems from not being able to target my $(el).each() on page load since it’s held in a different template, or possibly I have to reload my API calls every time I type in a URL. I imagine this isn’t enough data for someone to troubleshoot, so feel free to ask me more questions or check out a live (in development) version here
If you’re visiting the website, try a flow like this:
Conditions (main nav) -> Annual Wellness Exam -> Refresh or hit enter in URL bar

Checking if a URL contains a value with javascript

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.

Can i pass information through the URL when i am using jQuery Mobile?

I have a mobile application that opens an in-app browser that uses the URL to pass information to my server , like the deviceID.
For example the browser will open the web-page (jquery Mobile) : www.myserver.com/doWork.html#deviceID
On the server part using JavaScript inside the doWork.html file, I get the deviceID like this:
var userId = window.location.hash.substring(1);
Is it ok that i pass information using the hash # ? In jquery mobile the hash # is used to change between pages when someone uses the Multi-Page template structure . So i am afraid that maybe i should use something else , like a question mark (?) ?
Or its perfectly fine ?
NO. Stop using # for your data transfers. Let jQM do its thing. Don't disturb it. Use Query strings( adding ? in url). My advice is to stop using query strings (? tags) and # tags to send data to the next page. Handle it using localStorage. Its more secure compared to Query strings because the user wont see the URL change, so your sensitive data is hidden, at least to a little extent. localStorage is HTML5's API which is like a temporary storage set aside per domain. This data will persist until data is cleared in cache. Assuming you have an anchor tag which goes to dowork.html,
Go to Do work
Add an attribute for device ID in the tag itself, like this :
Go to Do work
You'd be doing this dynamically you might also use it the same way. You get the gist right?
A click event for this would look like this :
$(document).on("click", "a", function(e) //use a class or ID for this instead of just "a"
//prevent default
e.preventDefault();
//get device id from tag attribute
var deviceId = $(this).data("deviceid");
//set it in localStorage
localStorage["dId"] = deviceId;
//redirect
$.mobile.changePage(this.href);
});
Then, in the other page's pageinit (or any event), get the device id from storage and send the ajax call to the server.
//assuming #dowork is the id of a div with data-role="page"
$(document).on("pageinit", "#dowork", function() {
//get from storage
var deviceId = localStorage["dId"];
//make ajax call or server call with deviceId here
});
But, if you still want to use URL for this, look at this question. I've given a decent enough answer over there.
To pass variables to the server you should avoid using the # symbol because regardless of the framework you are using this symbol is used for other purposes, to pass info to the server in a GET request you should use the ? symbol, something like this should do it: www.myserver.com/doWork.html?deviceID=1233455

How to correctly read Javascript hash in custom affiliate URL?

I'm creating a custom affiliate program. I want my links to be as SEO friendly as possible, so I will use a Javascript hash appended to the URL to send the affiliate id, read the affiliate id, store the click, and then 301 re-direct to the page they were linked too. That way we have no canonical issues whatsoever, and every affiliate link passes link juice!
Now, how would I read the following URL?
www.mydomain.com/seo-friendly-url#ref=john
After getting the hash value for ref and adding the click, how would I then 301 re-direct the user back to
www.mydomain.com/seo-friendly-url
Any help is greatly appreciated!
Fragment identifiers (the part after the #) are not sent to the server, so they cannot be read by anything that could then emit an HTTP response (which you need for a 301 redirect).
The "hash" portion of a URL is not passed to the server, so you will not be able to utilize this data for any server-side redirection or processing directly. However, it is possible to grab the hash on page load and pass it on to the server via AJAX or redirection:
To immediately redirect a user from www.mydomain.com/seo-friendly-url#ref=john to www.mydomain.com/seo-friendly-url/ref/john
if (window.location.hash.match(/#ref=/))
window.location = window.location.href.replace('#ref=', '/ref/')
... but then, why not have just used www.mydomain.com/seo-friendly-url/ref/john to begin with and save the extra leg work? The other route, through AJAX, involves reading the value of the hash after the page has loaded and sending that off to the server to be recorded.
(note: this code uses a generic cross-browser XMLHTTPRequest to send an AJAX GET request. replace with your library's implementation [if you are using a library])
window.onload = function () {
// grab the hash (if any)
var affiliate_id = window.location.hash;
// make sure there is a hash, and that it starts with "#ref="
if (affiliate_id.length > 0 && affiliate_id.match(/#ref=/)) {
// clear the hash (it is not relevant to the user)
window.location.hash = '';
// initialize an XMLRequest, send the data to affiliate.php
var oXMLHttpRequest = new XMLHttpRequest;
oXMLHttpRequest.open("GET", "record_affiliate.php?affiliate="+affiliate_id, true);
oXMLHttpRequest.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE) {
// do anything else that needs to be done after recording affiliate
}
}
oXMLHttpRequest.send(null);
}
}

Categories