Cy.
Cy.

Reputation: 2145

Get URL parameters in JS and embed into a JS function

I have a graph library that I use to plot some data.

This data comes passed as a GET paramater in the URL in the following format: plottedgraph.html?case_id=4&otherparam=blabla

Then I have my HTML page where I try to catch that GET param with the GUP function (below) and add it to my JS function as follows: "http://www.url.com/showgraph.do?case_id=" + gup('case_id') + "&status=weighted"

This is the whole HTML

<html>
<head>
    <!--[if IE]>
      <script type="text/javascript" src="js/excanvas.js"></script>
    <![endif]-->
    <script type="text/javascript" src="js/dygraph-combined.js"></script>

    <script type="javascript">
    function gup( name )
    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return results[1];
    }
    </script>

</head>
<body>
<div id="graphdiv2" style="width:1800; height:900px;"></div>
<script type="text/javascript">
  g2 = new Dygraph(
    document.getElementById("graphdiv2"),
    "http://www.url.com/showgraph.do?case_id=" + gup('case_id') + "&status=weighted", // path to CSV file
    {
      showRoller: true,
      colors: ["rgb(255,100,100)",
               "rgb(72,61,139)"]
    }          // options
  );
</script>
</body>
</html>

Unfortunately the JS function doesn't recognize that case_id=4 in this case...

Could you please let me know what am I doing wrong?

Upvotes: 0

Views: 2938

Answers (1)

ivy
ivy

Reputation: 5559

It's a bit hard to debug you gup() function, could you try:

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

You can now find your parameters in the params object, so params['case_id'] will hold the value you're looking for.

Upvotes: 2

Related Questions