Jonathan Clark
Jonathan Clark

Reputation: 20538

Calling URL parameters within a .js file

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!

Upvotes: 9

Views: 17305

Answers (8)

tbone
tbone

Reputation: 5865

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));
    }
}

Upvotes: 0

n00b
n00b

Reputation: 16536

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&id=799

Upvotes: 0

Kuttan Sujith
Kuttan Sujith

Reputation: 7979

cshtml file

<script src="@Url.Content("~/_scripts/CustomScripts/Coverage.js")" type="text/javascript"></script>   
@using (Html.BeginForm("Create", "Coverage")) {

}    
<script type="text/javascript">    getTypeIDByCategoryIdUrl = '@Url.Action("GetTypeIDByCategoryId")';  </script>

Coverage.js

var getTypeIDByCategoryIdUrl = ""; $(function () {
      $('#SeletedParrentIDTypeCode').change(function () {
      alert(getTypeIDByCategoryIdUrl); }

Upvotes: 0

pixeline
pixeline

Reputation: 17974

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>\")";
?>

Upvotes: 7

Dan Inactive
Dan Inactive

Reputation: 10060

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).

Upvotes: 2

Teja Kantamneni
Teja Kantamneni

Reputation: 17472

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

Upvotes: 0

Nicolas Viennot
Nicolas Viennot

Reputation: 3969

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)

Upvotes: 1

Warty
Warty

Reputation: 7395

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.

Upvotes: 2

Related Questions