Get GET variables with javascript.

Usually if your working with froms your working with a server side language to take care of the really work involved (I prefer PHP for it) but what if you don’t wat to do it that way, or even can’t? Earlier this weel I was working on a little project that may eventually become an iOS game via PhoneGap and on it there is a form. I wanted this form to both go to another page, but gather and use the information input on that other page. I could have used ajax to reload the document in place but I didn’t really see the advantage of that, the usual speed increase it negligible when your loading all the files locally anyways. Neither Javascript or jQuery have methods in place for reading these get variables, but they do have the ability to rea the URL so with some creative breaking we can get them anyways.

Snipplr: http://snipplr.com/view/62892/get-get-and-post-variables-in-javascript/

I actually found that code before I was looking for it (initially I was hoping there was some built in way to do this I just wasn’t aware of, so I wouldn’t have to program the same thing). It works really simply, it takes the url, and using a regular expression breaks it down, giving you a nice PHP inspired $_GET variable to play with. You call it the same way you would in PHP, so if your familiar with that then it should feel right at home. Note that the code above leaves the spaces converted to +’s, you might want to add some .split() and .join() to it if you want it completely converted.

POST variables on he other had are a little more difficult and, infact, cannot be done with javascript alone. I didn’t really experiment with this as GET worked just fine for what I was doing but I did see some other people mentioning it, they all had the same idea, and it’s probably the simplest way to do it, just have PHP (or the server side language of your choice) turn the post varibles into an object, the simplest example being.

Snipplr: http://snipplr.com/view/62892/get-get-and-post-variables-in-javascript/

That code should create an object with all the same post variables, but I never tested it (again, not needed with my project). There is one glaring problem with it however, security. If your sending passwords over there then they will show up, in place test, in the HTML. Just something to keep in mind if your going to use this method. If you have any questions let me know and I’ll see what I can do.

Leave a Reply

Your email address will not be published. Required fields are marked *