4

I've got to code a webapplication for a university project. It's something like a calender using JSP, Javascript, Java, JQuery and SQL. So I've come pretty far, but i've got a Problem with my Query Strings. I am trying to give the Id of the clicked Cell on to another Page, which is supposed to look in the Database for an Entry with that id. I am Passing this Id through a QueryString, but can't get it out. I've tried everything. Every little Piece of Code, which was supposed to get the Parameters out. That's my latest try:

    var i = location.search.split('i=')[1];

to test if the parameter has been cut out, i've tried this, which isn't working...

    var x = document.getElementById("vname");
    x.setAttribute("value",i);

vname ist the id of an input field of the form on that site. Thanks for the help :) EDIT: My ID isn't just Integer it's something like this "fr21" for friday 21:00.

I've literally tried everything u recommended, but it's not working. If i use firebug on firefox it says: "ReferenceError: functionxyz is not defined" although it is... Don't know what to do.

Musti
  • 139
  • 1
  • 9
  • If you log the value of `i` in the console, what do you get ? – Ilya Dec 27 '15 at 21:41
  • Setting the `value` of an `` DOM element node should be just `x.value = i;`. – Pointy Dec 27 '15 at 21:43
  • How is query string set ? – guest271314 Dec 27 '15 at 21:47
  • (at)Ilya: don't know how to log :(.... (at)Pointy: I've tried that aswell, doesn't work either (at)guest271314: it's "site.jsp?i="+ident" where ident is the id of the clicked cell – Musti Dec 27 '15 at 22:03
  • Possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – WhiteHat Dec 27 '15 at 22:27

1 Answers1

1

Using an approach like split('i=') is not very robust. Better use regex and filter for the specific query string value like

<script>
  var matches = location.href.match(/&?i=(\w+)&?/);

  if (matches !== null)
  {
    var id = matches[1];

    alert(id);
  }
</script>

This way you have the advantage of supporting multiple query string parameters. So when a query string like abc=d&i=123&g=h is used, the script will return 123.

Edit

/&?i=(\w+)&?/ means

/ begin regular expression

&? match optional & character

i= i=

( start capture group, to read value later with matches[1]

\w match all characters A-Z, a-z, 0-9 and _

) close capture group

&? match optional & character

/ end regular expression

ViRuSTriNiTy
  • 5,017
  • 2
  • 32
  • 58