Sainath Krishnan
Sainath Krishnan

Reputation: 2139

Send variable to external PHP file from JavaScript

I have the following code to include in one domain (http://www.example1.com)

<script
    type="text/javascript"
    src="http://www.example2.com/API/incoming.php?id=560">
</script>

All this does is invoke the page incoming.php in my second domain (http://www.example2.com), and send it the value "560".

My questions are:

  1. Is it possible to send runtime variables to the page? (Eg : I am hard coding `560`, is there any way to get it dynamically if it is part of the URL?
  2. Would it be possible to send the page URL where this script was loaded? This is what I tried so far, but I am not able to access the variable URL.
<script type="text/javascript" src="http://www.example2.com/API/incoming.php?id=560">
var Url = "";
if (typeof this.href != "undefined") {
       Url = this.href.toString().toLowerCase(); 
}else{ 
       Url = document.location.toString().toLowerCase();
}
</script>

Upvotes: 0

Views: 274

Answers (1)

dreamlab
dreamlab

Reputation: 3361

you can create the script tag dynamically and pass all the variables you like via GET.

<script>
    (function() {
        var id = 560;
        var url = document.location.toString().toLowerCase(); // use other means if necessary

        var scriptElement = document.createElement('script');
        scriptElement.src = 'your.php?id=' + encodeURI(id) + '&url=' + encodeURI(url);
        document.body.appendChild(scriptElement);
    }());
</script>

the scriptElement will begin to load after it is inserted in the document.

this is how google analytics and others did or do it.

Upvotes: 2

Related Questions