0

I'm looking for a jQuery code which acts like PHP's $_GET. In a link like this http://example.com/index.php?page=pics&action=show I want to get the "page" and the "action" values. In PHP it will be easily done, but I need it in jQuery. I tried to get the whole url with $(location).attr('href'); but then I had to filter it, and I'm pretty sure that there is an easier way.

Thanks in advice.

Bankin
  • 777
  • 1
  • 16
  • 31
  • http://meta.stackexchange.com/questions/45176/when-is-use-jquery-not-a-valid-answer-to-a-javascript-question – bPratik Jul 18 '12 at 09:11
  • What you are trying to achieve has been answered here http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript – bPratik Jul 18 '12 at 09:12

2 Answers2

2

A lot of ways to do that are listed here. I recommend the JQuery URL Parser.

Just add the the URL parser script to your page and use it in the following manner

$.url('http://xyz.com?param1=abc&param2=def').param('param1'); // returns 'abc'
Community
  • 1
  • 1
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
1

I have done complete bins for above solution.

Follow Steps as below:

1) Include latest jquery.js file.

2) Include querystring-0.9.0.js for getting query string variable value in js.

3) HTML :

<a href="#?param1=abc&param2=def">
  abc
</a>

Here i have used "#?param1=abc&param2=def" because on bins it is not possible redirect page and execute our java script, so that i have just added query string on same page and test it.

4) jQuery in script tag:

$(function() {
    $("a").click(function() {
        setTimeout(function() {
            var param1 = $.QueryString("param1");
            var param2 = $.QueryString("param2");
            alert(param1);
            alert(param2);
        }, 300);

    });
});

Above script is working fine, if query strings has been added on the same page, but for the different page navigation, you have to remove setTimeout function but keep script as it is inside in it and execute these statements as below on the page where you navigates with query string. so, the different navigation has needs to be included jquery and querystring-0.9.0.js both java script files in header first.

 $(function() {
           var param1 = $.QueryString("param1");
           var param2 = $.QueryString("param2");
           alert(param1);
           alert(param2);
 });

You can try on http://codebins.com/bin/4ldqpac

gaurang171
  • 9,032
  • 4
  • 28
  • 30