Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 862
Jonathan Clark Avatar asked Feb 24 '10 19:02

Jonathan Clark


People also ask

Can you use Javascript to get URL parameter values?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.

How do you hit a URL in Javascript?

To make an HTTP call in Ajax, you need to initialize a new XMLHttpRequest() method, specify the URL endpoint and HTTP method (in this case GET). Finally, we use the open() method to tie the HTTP method and URL endpoint together and call the send() method to fire off the request.

How do you give a URL parameter?

To identify a URL parameter, refer to the portion of the URL that comes after a question mark (?). URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).

How do I link a Javascript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.


2 Answers

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>\")";
?>
like image 196
pixeline Avatar answered Oct 26 '22 03:10

pixeline


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.

like image 22
Warty Avatar answered Oct 26 '22 02:10

Warty