3

I am trying to pass a javascript variable to a php page via the URL. The code below triggers the php page but it doesn't get the variable. I have written the code using window.location.href and that works fine, the problem is doing it that way it loads the tracker.php page.

Below is my code.

<script type="text/javascript">
var siteId = "VT0013";
</script>
<script type="text/javascript" src="http://www.domainame.com/tracker.php?siteId="+ siteId ;> 
</script>

PHP Page

$siteId = $_GET["siteId"];

Once I get the siteId I email the result as a test this works fine, except I am not getting the value of siteId. When using this same code with window.location.href it all works fine.

3 Answers 3

1

I'm guessing that since this is called tracker.php, you actually just need to hit this URL? If that's the case, consider using the Beacon API.

navigator.sendBeacon('https://example.com/tracker.php' {
  siteId: 'VT0013'
});

This results in an HTTP POST request, but that's generally better for this anyway. You won't have to worry about caching. Also, the Beacon API will still work even if the request hasn't finished and the page is being unloaded.

If you actually do want to dynamically loads JavaScript instead, a current way to do that is to use import().

const siteId = 'VT0013';
await import (`https://example.com/tracker.php?siteId${encodeURIComponent(siteId)}`);

Finally, if you need to dynamically load this JavaScript and that script needs to run in the context of the rest of the page (i.e., not a module) then the best thing to do is inject a new script tag: https://stackoverflow.com/a/8578840/362536

No matter what you do, make sure you're escaping the data used in your URLs and in your HTML.

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

4 Comments

Don't use document.sendBeacon(). It does not download and execute scripts, and in old browsers it will cause an error halting any JavaScript code that follows it. You would be remiss to not support browsers like Internet Explorer and other old browsers because literally millions of people still use them. Injecting a script tag might work, but only if the script can be loaded asynchronously.
@PHPGuru As I said in my answer, the beacon API is suitable only if making a request to that URL is all that's needed. As for browser support, it depends on your needs. The Beacon API has been supported for many years. caniuse.com/beacon It's up to the developer to figure out a solution appropriate for their specific use case, which is why I explain the tradeoffs.
This is a superior solution to mine, albeit overtly modern. Great answer! For those wanting a quick, old-school way that does support IE outta the box then my answer will hopefully cover that.
@Brad I'm guessing you're right that the OP just needs to hit a URL and Navigator.sendBeacon() would work for that. But it has only been around for a few years. If you just need to hit a cross-origin URL, the best way to do that is to create a new image with new Image() and then modify its src property which works on all browsers. You also shouldn't use import for something like this because it isn't needed for such a simple task and won't work on old browsers. You'd be better off injecting a script tag assuming the script is able to run asynchronously which was not implied but is not unlikely
0

You can just do a quick XHR request if you want older browser support without polyfills:

var siteId = 'VT0013'; 
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

xhr.open('GET', 'http://www.domainame.com/tracker.php?siteId=' + encodeURIComponent(siteId));
xhr.send();

This is just an alternate solution, @Brad's answer should be accepted.

1 Comment

This will only work if your tracker is on the same origin. To make it work on a third party origin you need an appropriate Access-Control-Allow-Origin response header and a modern web browser. If you're just trying to load a third party tracker, there are better ways.
-2

You need to use document.write to write any HTML that contains JavaScript variables:

<script type="text/javascript">
var siteId = "VT0013";
document.write('<script type="text/javascript" src="http://www.domainame.com/tracker.php?siteId='+encodeURIComponent(siteId)+'">
<\/script>')
</script>

This is the equivalent of writing

<script type="text/javascript">
var siteId = "VT0013";
</script>
<script type="text/javascript" src="http://www.domainame.com/tracker.php?siteId=VT0013"></script>

Edited to properly escape JavaScript variable.

Please note that it is not advisable to use document.write to load scripts from a third-party domain because Google Chrome might choose not to load the script if the connection is too slow. See https://developers.google.com/web/updates/2016/08/removing-document-write.

If the script can be loaded asynchronously, I recommend this method instead because it will not slow down the HTML parser:

<script>
var siteId = "VT0013";
(function(d, s){
    s = d.createElement("script");
    s.src = "http://www.domainame.com/tracker.php?siteId="+encodeURIComponent(siteId);
    d.getElementsByTagName("head")[0].appendChild(s);
})(document)
</script>

3 Comments

Don't use document.write(). stackoverflow.com/q/802854/362536 There are far better methods. Additionally, as with the other answer here, you're likely enabling XSS. You need to escape your data if you're going to use it in the context of HTML.
If he doesn't use document.write, the script won't be loaded synchronously like it is in his example. There is nothing wrong with using document.write in this case.
@Brad I updated my answer to address the problems you pointed out.

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.