-2

Hey i am trying to get value from url in javascript variable. Here is the demo url : http://localhost/product.php?prod_id=MQ==&action=add Now i want to access the prod_id (MQ==) from the url and then decode it and store it in javascript variable. Can anyone help me out in implementing this ? Thanks in advance.

  • 1
    what is your approach? what are your problems? – Thomas Apr 13 '16 at 19:19
  • 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) / Base64 decoding comes after that – and should be easy enough to _research_ as well. – CBroe Apr 13 '16 at 19:24

3 Answers3

2

First, you must escape your base64 string because there are valid base64 characters are that are used in query strings (= for example). You can do this with escape() in javascript.

Next, you'll need to parse the query string, and unescape() the value to get the base64 string again. Parsing the query string is probably out of scope for this question as there are many resources on the web.

To parse the string, first grab the string from location.search and that will return the query string (including ?). Since you don't need the '?' I suggest using .substring(1) to trim it off. Next, you'll want to split() the strings on the ampersand '&' so that you'll get an array like: ['prod_id=MQ==', 'action=add']. Finally, take each string in that array and split it on the first '=', which will give you an Array(2) where the first is the key and the second is the value.

Rob Brander
  • 3,702
  • 1
  • 20
  • 33
  • 1
    Note: `escape()` is deprecated. Use `encodeURIComponent()` or `encodeURI()` if you can (Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape). – Chrisuu Feb 23 '23 at 18:22
1

This will work in modern browsers. It can also be made to work in IE 10 if you replace the arrow functions with normal functions:

function getFromQueryStringAndDecode ( query ) { 
    var base64 = location.search.substr( 1 ).split( /&/g )
      .map( x => x.split( /^([^=]*)=/ ).slice( 1 ) )
      .filter( x => x[0] === query )[0][1]
    ;
    return atob( base64 );
}

// Usage:
getFromQueryStringAndDecode( 'prod_id' ); // '1'
Paul
  • 139,544
  • 27
  • 275
  • 264
-1

First get the value from the url into a php variable like this :

<?php
  $x = base64_decode($_GET["prod_id"]);
?>            

Then save this value into a hidden text field like this :

<input type="hidden" id="product_id" value="<?php echo $x; ?>">

Then get this value from the hidden textfield to javascript variable.

$(document).ready(function(){
    $value = $("#product_id").val();     
}
Harshit
  • 50
  • 7