-3

Assuming an HTML web form with 2 hidden fields.

landingurl: the full url where the visitor landed before submitting the form including tracking codes

referealurl: the full referal url (where the visitor came from)

I want to jquery to save those values in the value fields which are hidden in the form.

I can't figure it out

Community
  • 1
  • 1
sebas
  • 722
  • 1
  • 6
  • 21
  • How are you expecting to grab the referral url? Afaik, by default that would be on the page load headers, and javascript wouldn't have access to those. – Taplar Jan 15 '19 at 22:27
  • how about grabing the landing page url? – sebas Jan 15 '19 at 22:33
  • 1
    The url of the current page is just `window.location.href` – Taplar Jan 15 '19 at 22:34
  • 1
    Unfortunately, the answer is **you can't**. Response headers are not exposed for the current page request. This has been [asked repeatedly](https://stackoverflow.com/questions/12258705/how-can-i-read-the-current-headers-without-making-a-new-request-with-js). – Cue Jan 15 '19 at 22:35
  • how to save the landing page url or current url in the hidden field before submitting – sebas Jan 15 '19 at 22:36

1 Answers1

1

You can grab the current URL with window.location.href, so if you grab the href on the landing page, then you have the landing URL.

You can grab the referring URL with document.referrer. This also needs to be grabbed on the landing page.

I haven't used jQuery in a while, but I believe the syntax would be something like this:

// For this example I have assumed your fields have the IDs landingURL and referralURL.

$('#landingURL').val(window.location.href);

$('#referralURL').val(document.referrer);

Now, if the landing page is not the same page as the form, and you need to pass this information along to the form page using only JavaScript in the browser, then I would suggest that you grab the landing page URL and the referral URL as described above and save them in either localStorage or sessionStorage.

Here's an example of how you can do that:

// On the landing page:
localStorage.setItem('landingURL', window.location.href);
localStorage.setItem('referralURL', document.referrer);

// On the form page:
$('#landingURL').val(localStorage.getItem('landingURL'));
$('#referralURL').val(localStorage.getItem('referralURL'));

Hope that helps!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Azer
  • 1,200
  • 13
  • 23