2

What I'm wanting to do is take a URL like myurl.com/page.php?data1=x&data2=y&data3=z and get each piece of data and use it in a jQuery function. Is there any built in way to do that?

To clarify, when I navigate to (say, pasting the url into the address bar, or going to it via a bookmark) I want jQuery to do something with that data.

As a bonus, if it also includes something to check if the data is set to something, that would be great.

Samsquanch
  • 8,866
  • 12
  • 50
  • 89

3 Answers3

3

You're looking for how to get values from the query string. Here's pretty much the same question:

How can I get query string values in JavaScript?

Community
  • 1
  • 1
JustcallmeDrago
  • 1,885
  • 1
  • 13
  • 23
2

A quick way to do it would be if your javascript code is embedded in a php file (not an external link to a .js file), you could just do a PHP print right in between your <script></script> tags. It would work with bookmarks and pasting the URL to the address bar.

For example:

<script type="text/javascript">
var get_var;
get_var = <? print $_GET['varname']; ?>;
// some jQuery code here
</script>

This should only be used as a proof of concept. This is vulnerable to XSS attacks, and should not be used in production. This list of XSS prevention techniques is a good place to start (but outside the scope of the OP's question).

Benjamin Smith
  • 877
  • 1
  • 9
  • 24
  • I think that might actually work exactly like I need. Not sure why I didn't think of that. Thanks. – Samsquanch Nov 03 '10 at 03:04
  • 2
    Though, be smart - this is not very practical as it is extremely vulnerable to code injection. – Dave Kiss Nov 03 '10 at 03:05
  • At current, this is mostly a proof of concept. But for code going live, I agree, and would come up with something a bit better. – Samsquanch Nov 03 '10 at 03:22
1

Perhaps a plugin like jQuery.url.js would work or maybe Url parser.

Craig
  • 706
  • 6
  • 8