Need help in getting the values of parms passed from URL with JQuery

116 Views Asked by At

I need help in getting the values of passed parms using Javascript from a url. In my Index html I defined the following:

<body bgcolor="#ffa800" background="file:///c:/website/images/background.jpg">

<script src="jquery-1.10.2.min.js"></script>
<script>
  alert("Initializing the Cart");
  var params = { cart1:1 };
  var cart1 = jQuery.param(params);
  alert(cart1);
</script>

Then I try to call another webpage from my index html:

       <a href="file:///c:/website/pages/vision.html?cartx=cart1&"> 

My alert shows cart1=1

In the other webpage vision.html I have:

<head>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
  <title>Vision</title>
      <script src="jquery-1.10.2.min.js"></script>
    <script>
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
}
return vars;
}
function checkcart()
{
  alert("Checking cart");
  var cartstatus = getUrlVars()["cartx"];
  alert(cartstatus);
}
</script>
</head>

<body  onload="checkcart()"  bgcolor="#F0FFF0">

My alert for cartstatus shows: cart1 I'm don't know why the value of cart1 is not given. Thanks in advance.

2

There are 2 best solutions below

0
On

Change this line in key=value format for cart=1

<a href="file:///c:/website/pages/vision.html?cartx=cart1&">

As below

<a href="file:///c:/website/pages/vision.html?cart=1">

And change this line

var cartstatus = getUrlVars()["cartx"];

As below and check

var cartstatus = getUrlVars()["cart"];

jsFiddle

0
On
var cartstatus = getUrlVars()["cartx"];

Change name of your variable you pass, when you get it from array as a key

file:///C:/Users/fs/Desktop/1.htm?cartx=3

Works great, when your variable is 'cartx'

Result:

enter image description here