-3

Possible Duplicate:
How can I get query string values?

I Have this link

url/merchant.html?id=45

I am trying to get the ID using JS or JQuery with no luck.

I tried this code

var urlParams = {};
(function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

it returns "undefined"

What is the problem with the code?

Community
  • 1
  • 1
Mohammad Ereiqat
  • 165
  • 1
  • 11

2 Answers2

1

Use this here:

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

so in your case:

getParameterByName("id")

From: How can I get query string values in JavaScript?

Community
  • 1
  • 1
Stefan
  • 2,164
  • 1
  • 23
  • 40
0

I wrote this function awhile back:

/**
 * Retrieves the value of a query string parameter.
 * @param string href The full URL
 * @param string key The key in the query string to search for.
 * @param variant def The default value to return if the key doesn't exist.
 * @returns variant if key exists returns the value, otherwise returns a default value.
 */
function getURIParam(href, key, def) {
    if (arguments.length == 2) def = null;
    var qs = href.substring(href.indexOf('?') + 1);
    var s = qs.split('&');
    for (var k in s) {
        var s2 = s[k].split('=');
        if (s2[0] == key)
            return decodeURIComponent(s2[1]);
    }
    return def;
}

You would use it like this:

var href = "http://www.example.org?id=1492";
var id = getURIParam(href, "id", 0);
//Output of id: 1492

If the key doesn't exist:

var href = "http://www.example.org?id=1492";
var name = getURIParam(href, "name", "Unnamed");
//Output of name: Unnamed
crush
  • 16,713
  • 9
  • 59
  • 100