get GET and POST variables in javascript


/ Published in: JavaScript
Save to your folder(s)

Usually when working with form you use a server to handle it, and if your doing it entirely in javascript no reload is required, but what if you wanted to take the information and use it in a javascript on another page, completely client side. I had that problem, and found this solution.

First is how to get GET variables in javascript, it works by breaking down the URL location with a regular expression giving you a variable that behaves like the PHP $_GET variable.

Second is for POST variables and, unfortunately requires a server side script to work since javascript has no way to acces the POSt on it's own. The code below is for PHP, but should work for any language, it is also untested as I was really aiming for GET at the time.

And questions, comments, or concerns let me know here or at the link, you'll find a bit more information this there as well.


Copy this code and paste it in your HTML
  1. // Getting GET variables (completely javascript(
  2. var $_GET = {},tokens,re = /[?&]?([^=]+)=([^&]*)/g;
  3. while(tokens = re.exec(document.location.search)) {
  4. $_GET[decodeURIComponent(tokens[1])]=decodeURIComponent(tokens[2]);
  5. }
  6.  
  7.  
  8. // Getting POST variables (using php to create the javascript object)
  9. echo json_encode($_POST);

URL: http://fatfolderdesign.com/528/code/get-get-variables-with-javascript

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.