Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get GET and POST variables with JQuery?

How do I simply get GET and POST values with JQuery?

What I want to do is something like this:

$('#container-1 > ul').tabs().tabs('select', $_GET('selectedTabIndex')); 
like image 802
Edward Tanguay Avatar asked Jan 13 '09 15:01

Edward Tanguay


People also ask

What is GET and POST method in jQuery?

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

How to POST data using jQuery?

The jQuery post() method sends asynchronous http POST request to the server to submit the data to the server and get the response. Syntax: $. post(url,[data],[callback],[type]);


1 Answers

For GET parameters, you can grab them from document.location.search:

var $_GET = {};  document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {     function decode(s) {         return decodeURIComponent(s.split("+").join(" "));     }      $_GET[decode(arguments[1])] = decode(arguments[2]); });  document.write($_GET["test"]); 

For POST parameters, you can serialize the $_POST object in JSON format into a <script> tag:

<script type="text/javascript"> var $_POST = <?php echo json_encode($_POST); ?>;  document.write($_POST["test"]); </script> 

While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:

var $_GET = <?php echo json_encode($_GET); ?>; 

Note: You'll need PHP version 5 or higher to use the built-in json_encode function.


Update: Here's a more generic implementation:

function getQueryParams(qs) {     qs = qs.split("+").join(" ");     var params = {},         tokens,         re = /[?&]?([^=]+)=([^&]*)/g;      while (tokens = re.exec(qs)) {         params[decodeURIComponent(tokens[1])]             = decodeURIComponent(tokens[2]);     }      return params; }  var $_GET = getQueryParams(document.location.search); 
like image 154
Ates Goral Avatar answered Oct 29 '22 00:10

Ates Goral