views:

663

answers:

9

Hello!

I am calling a .js file within a HTML file. On the URL to the .js file I want to include a parameter that will be accessable to the code INSIDE the .js file.

For example:

I want to be able to pass the ID value to a function within the jquery_widget.js file, with the help of jQuery. How is this done?

Thankful for all help!

+2  A: 

You use something like php

your html file:
<script type="text/javascript" src="yourFile.php?var=123">  

yourFile.php:  
// <?php echo($_GET["var"]); ?>

Or, you could define a global variable and have the javascript access that variable.

ItzWarty
+3  A: 

You can't do it like that: you have to declare the variable before loading the script. Example:

<script type="text/javascript">
var foo= "bar";
</script>
<script type="text/javascript" href="path/to/js.js"></script>

in this way, the variable will be ready for your script.

Another solution is to use a php script, that can then use the GET variable. In that case, make sure you tell via a header() call that you are outputting javascript

<script type="text/javascript" src="ip.php"></script>

And the ip.php

<?
//"ip.php" example- display user IP address on any page
Header("content-type: application/x-javascript");
$serverIP=$_SERVER['REMOTE_ADDR'];
echo "document.write(\"Your IP address is: <b>" . $serverIP . "</b>\")";
?>
pixeline
+1  A: 

Approach the problem differently:

  1. Include your .js file
  2. Call a function defined in your .js file with a parameter (i.e. your ID value)
Nicolas Viennot
A: 
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}

Source: http://snipplr.com/view.php?codeview&amp;id=799

n00b
that will not work .. he is asking for url parameters to the `.js` inclusion .. not to the html page..
Gaby
A: 

HTML and javascript files are static resources and will be interpreted only by the client browser, so you can't pass any query params to these values and read them inside, What you can do is dynamically generate your javascript files with params at serverside and then include it as part of the page. Or other simple way is write your js file as a php or jsp file and set the content type of the page to text/javascript and you can access all the params inside it

Teja Kantamneni
A: 

If you're trying to read parameters from the url, I've used:

function PageQuery(q) {
    if (q.length > 1) this.q = q.substring(1, q.length);
    else this.q = null;
    this.keyValuePairs = new Array();
    if (q) {
        for (var i = 0; i < this.q.split("&").length; i++) {
            this.keyValuePairs[i] = this.q.split("&")[i];
        }
    }
    this.getKeyValuePairs = function() { return this.keyValuePairs; }
    this.getValue = function(s) {
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            if (this.keyValuePairs[j].split("=")[0] == s)
                return this.keyValuePairs[j].split("=")[1];
        }
        return false;
    }
    this.getParameters = function() {
        var a = new Array(this.getLength());
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            a[j] = this.keyValuePairs[j].split("=")[0];
        }
        return a;
    }
    this.getLength = function() { return this.keyValuePairs.length; }
}
function queryString(key) {
    var page = new PageQuery(window.location.search);
    return unescape(page.getValue(key));
}
function displayItem(key) {
    if (queryString(key) == 'false') {
        document.write("you didn't enter a ?name=value querystring item.");
    } else {
        document.write(queryString(key));
    }
}
tbone
+1  A: 

Here's a nice tutorial:

Passing JavaScript arguments via the src attribute

karim79
Yep, something like that :)
Dan
A: 

The javascript file by itself is not aware of the URL it's being loaded from.

What you can do is assign an ID to the script tag you're including in the HTML page, and then grab the SRC attribute through jQuery. By parsing the URL value, you can extract the parameter.

<script id='widgetJs' src='...'></script>

var url = $("#widgetJs").attr("src");
var q = url.split("?")[1];
if (q) {
    var params = q.split("&");
    etc. etc... 
    i'm not even going to explain further because there are better solutions.
}

A simpler solution is to declare a global variable in a separate script tag (namespace it to avoid conflicts) and then use it directly in your script.

Or better yet, have an initialize(param) function in your script that you invoke from the HTML file (this saves you from polluting the global context with unnecessary variables).

Dan
A: 

Works fine now! Thanks for all help. I used the code from the first answer and it worked fine!

Jonathan Clark