00:00
00:00
B1KMusic
Hi. I make games and software. I'm not on NG much, but feel free to peruse my youtube and gitlab for interesting stuff.

Braden @B1KMusic

Age 29, Male

Programmer/Musician/

fish

Earth, Milky Way

Joined on 6/19/11

Level:
10
Exp Points:
948 / 1,110
Exp Rank:
69,221
Vote Power:
5.20 votes
Rank:
Police Sergeant
Global Rank:
8,619
Blams:
42
Saves:
1,040
B/P Bonus:
12%
Whistle:
Normal
Medals:
799

Moar ways to do $_GET in javascript / Link saver thing I made

Posted by B1KMusic - September 2nd, 2012


Are you a Web Developer? Have you always wondered "well GEE, I dunz know php, so how da fuck do I get $_GET for javascript? HOW U DO IT GOOGLE!?"?

K, check dis shit out, then.

First of all, there are two ways you can get a parameter from the URL. Well, if you wanna be a nit-picking literal sonofabitch, there are nearly infinite ways with minute differences that you can make this possible, but I digress.

One way is via function (which has been done to death, but if you want that one, check the end of this post), and one that I wrote after pondering, how do i REPLICATE php's $_GET so I can use $_GET['key'], notice the square brackets.

I wrote this code to emulate php's $_GET variable.

Before I give the snippet, I'ma explain the concept:

php grabs variables from the url via a variable called $_GET, which is an array of every key/value pair in the query string, referred to in javascript as an "Object".

Can javascript do this? Let's see:

Arrays. Check

Objects. Check

Url access. Check

Goal: create an object called $_GET, and fill it with the relevant information in the URL (while remaining nice and compact), and this is what I came up with in about 20 minutes:

/***START GET***/
try{
$_GET={}
query=location.search.split('&')
for(i in query){
reg=RegExp('([^=?&]*)=([^=?&]*)').exec(query[i])
$_GET[reg[1].replace(/%20/g,' ')]=reg[2].replace(/%20/g,' ')
}
}catch(e){/*No query string*/}
/***END GET***/

Breakdown:

try{...catch(e){...} Obviously, your website won't always have a query string (what's after the ? symbol), so this is to prevent errors

$_GET={} The first thing that must be done is defining a global, empty object to HOLD this information, otherwise it's useless

query=location.search.split('&') This splits between every & symbol and returns an array of every raw key/value pair, the lack of ? is intentional, as that would make query[0] equal to '', and make it so you have to use a few workarounds (such as array[i+1]) to do this, and it also means that you can't use a for..in loop, as there is no such thing as array['01'], unless you want to put array[parseInt(i)+1], but remember that I also want this to be compact, so that noise is out of the question.

for(i in query){
...
}
this for loop runs through the array, query, to grab every query string object

reg=RegExp('([^?&=]*)=([^?&=]*)').exec(query[i])

Yeah, if you don't understand Regular Expressions, this will probably make zero sense to you, and I feel like trying to explain it will waste time, mine and yours. But in a short summary, it's in the exec function, which can basically grab a value from the ANYWHERE you want in a string. Insanely useful function.

I don't know if you remember the split('&') from a while ago, but that left a '?' at the beginning of the first kv pair, this takes care of it by telling the exec function to ignore ALL ?'s

and the coup de grace, what all this build up was for,

$_GET[reg[1].replace(/%20/g,' ')]=reg[2].replace(/%20/g,' ')

The bare version of this is $_GET[reg[1]]=reg[2], but I thought spaces might be wanted instead of %20, hence the replace function.

Of course, the syntax is exactly the same as its php counterpart, and it will even exclude vars with '?' before them (when a '&' should be behind them) somehow (a "happy accident", if you will).

I made a demonstration file which writes everything in the url on the screen. get it HERE. This should work in any browser, as I write my code in a "weird" minimalist manner that works on anything. Yes, even the horrid Internet Explorer should run this without a problem. However, the browser I tested this on was Google Chrome, for its awesome F12 console, so if it for some reason DOESN'T work on IE, google chrome/any non-trident browser is the next best bet.

And I didn't forget the function.

The most basic form of it is this:

$_GET=function(key){
try{
return RegExp('[?&]'+key+'=([^?&]*)').exec(location.hre f)[1].replace(/%20/g,' ')
}catch(e){
return ''
}
}

what it does is, instead of creating a readily-available list of keys, it grabs a key based on what you request, so say you have a url, http://yoursite.com?ref=bullshit.com, and in javascript, you request $_GET('ref')

Short version: it will return 'bullshit.com'

Long version: it finds and looks after ? or & for key (in this case, 'ref'), and then it grabs as many non-?/& symbols as possible (([^?&]*)), and returns the result. Again, if you have a poor grasp of RegExp, you won't understand this.

I have a file from another post that uses this $_GET function, so here is that as well so you aren't left in the dark. You'll notice it also pulls off $_POST. Read this post to get more info on that.

__________________________

Also, do you find yourself saving a LOT of links into notepad like I do? If so, then you'll love this...thing I wrote. There's a screenshot below.

It has a lot of bells n whistles, so I don't know if you'll be able to figure out how to use everything, so for starters, TOP ROW, Clicking the [+] on the top will allow you to add another link to the list, and clicking the [~] on the top allows you to create categories for your links. The default is links and faves because a few browsers I tested it on (like Maxthon) when I implemented that had a weird glitch when there was only one default category, links, that would cause the list to write itself into itself, causing some stupid bullshit to happen >:(. The [-] button allows you to remove a category from the list.

BOTTOM ROW. The Clear button deletes every link in the currently selected category. The [+] and [-] buttons on the bottom will "show" and "hide" links on the list. I added this after being annoyed with all the "REMOVED" links clogging up the list. It helps make everything neat. This is the same reason I created the Swap feature, which I will Deliberate on later. The [~] link on the bottom is a little pointless, but it changes the "animation" for the top row buttons. The [S] link stands for Swap, it will swap two of the links with each other. I created this when I got fed up with A) the REMOVED links in the center, which clicking [-] on wouldn't just magically make go away, and B) not being able to sort the links' positions. The [X] button reveals and hides extra options for the [+], [-], and [~] buttons on the bottom row.

BOTTOM BOTTOM ROW. The Clear Everything Button. This has a little bastard of a button which is so evil and dangerous that I not only put it under extra options, but also both didn't bother finishing coding it to delete everything and deliberately made it a pain-in-the-ass to even click. Don't bother with it, all it does is what the normal Clear button does, plus deleting the category list and effectively leaving a shit ton of junk data on your computer. It's broken.

If you have the little patience needed to get used to this and end up using it a lot, then nothing would be worse than losing all those links for some reason (which has never happened to me so far, but I digress). Anyways, I also decided to quickly design a storage writer of sorts to dump everything from localStorage to a textarea, this can be saved to notepad to later restore everything. All that has to be done to restore it is 1) Copy the saved text from the notepad document you saved it in. 2) Paste the source into the text field where you originally got it. 3) Click the "Restore Storage" link above the text field.

Download link here (Update Sept. 8 2012: added Save and Restore Functionality and bugfix involving apostrophes.)

You can also transfer the data between computers and browsers with this Storage Writer Using the Restore link (Use the "Save Storage" link to merge existing storage rather than overwrite it).

All in all, I have found this to be very useful, and am glad I made it. Hopefully you will enjoy it, too.

HOWEVER...

Continuing the thought of how the stuff I write works on every browser I've heard of, there is one exception:

Internet Explorer has a shitty tendency to NOT working with HTML5 Web storage on localhost. Oh yeah, you heard me right, INTERNET EXPLORER CANT HAZ SAVE. Instead, you have to download XAMPP and run a file using local/sessionStorage through the apache virtual host. This is because for some stupid, retarded, money whoring reason, Microsoft thought it was a good idea to design their browser to only save cookies and Storage if it's running on a server, but not on the local machine. It can't Save Storage on the local machine, you know, what EVERY OTHER BROWSER does jut by rule of common sense. Firefox does it; safari does it; Chrome does it; Maxthon does it; opera does it; so why doesn't IE do it?

So yeah, run this and other "saver" apps on chrome (or any other webkit browser) for the best result. Unless you know how to run XAMPP...but you'd have to also edit the file and change every reference to "e" to event.keyCode since IE is a nit-picking fuck with that, too.

Moar ways to do $_GET in javascript / Link saver thing I made


Comments

Comments ain't a thing here.