2

I am trying to alert the querystring param in jquery because i need that ID on a page load so that i can create some html elements when the control is loaded. I cant seem to access the parameter as the URL rewrite in place and URL looks diff then the original one.

Original URL

www.somesite.com/camping?ProductId=2457&ism=0&cl=PURPLE

URL seen in browser

www.somesite.com/camping/travel-mug-16oz-double-wat-with-adapter-p2457.aspx?ism=0&cl=PURPLE

now, how do i access the ProductId querystring value in Jquery.

Jquery

$(document).ready(function () {
      var param = getParameterByName("ProductId");
     alert(param) // shows PURPLE as cl in URL is set to cl=PURPLE

});

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

EDIT:

here is the screenshot when i am trying to access the Querysting object on serverside..

enter image description here

3
  • I don't exactly know what URL rewrite is but the URL given to the browser does not have a ProductID query string. Javascript cannot see onto the server without the server providing access, would you be able to access this via Ajax? Commented Oct 22, 2013 at 12:19
  • that is what i am trying to understand... how can i access the actual URL via jquery? Commented Oct 22, 2013 at 12:21
  • As far as Javascript is concerned the first URL never existed, it has only been given the second one, if you have the "Actual" URL stored on the server you can access this via Ajax. Commented Oct 22, 2013 at 12:23

1 Answer 1

1

Your current code is attempting to access the value from the querystring, which no longer exists as it has been rewritten on the server.

You can use a regular expression to dissect the rewritten URL, no jQuery required. Assuming your productId is always prefaced by -p and is immediately followed by .aspx, then this will work:

var url = 'www.somesite.com/camping/travel-mug-16oz-double-wat-with-adapter-p2457.aspx?ism=0&cl=PURPLE'
var matches = url.match(/-p(\d+)\.aspx/);
var productId = matches && matches[1];
console.log(productId); // = 2457

productId will be null if there are no matches to the regex.

Example fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Yes @Rory, i think this is the case... productId will always be prefaced by p- BUT not sure about the .ASPX thing BUT i assume this is the case...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.