-1

I'm trying to set up a referral program for users of a site. Each one currently gets a referral link like this: mysite.app/user/signup/?ref=123456789

On each signup, I need to slice that URL ?ref parameter 123456789, assign it to the variable ref and push it to a form input field with the id=hiddenref.

I have the script below from a tutorial but I can't get it to work and I suspect it might be because it was meant for a URL with a folder structure like this: mysite.app/?ref=123456789.

Any help would be appreciated!

<script> 
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
        else return "none";
    }
};

ref = getUrlParameter('ref'); 
document.getElementById('hiddenref').value = ref;
</script>
  • Does this answer your question? [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – bill.gates Mar 29 '20 at 12:28

3 Answers3

2

You can use URL class

var u = new URL(location.href);
u.searchParams.get("ref")

it will return

123456789
0

You can use below util method.

const getQueryParams = url => {
  const match = url.split(/\/?\?|#/)[1];
  if (!match) return;
  return match.split(/&/g).reduce((m, v) => {
    const [key, val] = v.split("=");
    m[key] = val;
    return m;
  }, {});
};
const params = getQueryParams(
  "https://flank.xyz/contact/thank-you/?loginId=xsf234-22f8-48d3-c3d3-08d7c7f8b488&tag=17&xyz=123#&xyz=456"
);
console.log(params.xyz);
console.log(params.loginId);

const params2 = getQueryParams(
  "https://flank.xyz/contact/thank-you/?loginId=xsf234-22f8-48d3-c3d3-08d7c7f8b488&tag=17&xyz=123"
);
console.log(params2.xyz);
console.log(params2.loginId);
.as-console-row {color: blue!important}
xdeepakv
  • 7,835
  • 2
  • 22
  • 32
  • It seems incomplete to me as it doesn't handle the URL fragment part correctly: `getQueryParams('http://example.com/abc?xyz=123#')` is `{x: '123#'}` instead of `{x: '123'}`, `getQueryParams('http://example.com/abc?xyz=123#&xyz=456')` is `{x: '456'}` instead of `{x: '123'}` – CherryDT Mar 29 '20 at 11:52
  • 1
    haha. let me update, He doesn't had that case. – xdeepakv Mar 29 '20 at 11:55
  • True but it looks like a generic utility function to extract a query from an URL, not from "the OP's URL only", so it would be best if it would actually work on any URL, since other people than the OP may find it in the search/on Google! – CherryDT Mar 29 '20 at 12:00
  • oh and may I add that it would be good to add `decodeURIComponent` to the values...! – CherryDT Mar 29 '20 at 12:02
  • @CherryDTUpdated solution, Too much over engineering. i don't like :-D – xdeepakv Mar 29 '20 at 12:05
  • @CherryDT @xdeepakv thanks for the help. I've tried to make it work, but my input field ends up with "[Object object]" using this: `` Am I grabbing the URL in the wrong way with `window.location.search`? – Thomas Christensen Mar 29 '20 at 14:06
  • You have to get desire tag: params.ref `const params = getQueryParams(window.location.search); document.getElementById('hiddenref').value = params.ref; ` – xdeepakv Mar 29 '20 at 14:15
  • That worked! I'm no JS expert, but do you think this would be more robust? `function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); } let ref = getParameterByName('ref'); document.getElementById('hiddenref').value = ref;` – Thomas Christensen Mar 29 '20 at 14:27
  • This was mentioned in this post: [link](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) as the right solution. – Thomas Christensen Mar 29 '20 at 14:27
-1

The hacky, easiest way:

let ref = window.location.split('?ref=')[1]

This is obviously prone to error. A much better way is described in this answer.

Dimitrie
  • 124
  • 5