PDA

View Full Version : JS file reading its own query strings



fileserverdirect
11-10-2007, 04:40 PM
Hello,
I am currently using a J.S. file that needs information from the parent document. So I decided to add ?var=value to the end of the url:
<script type="text/javascript" src="myfile.js?var=value"></script>
Then I googled a GET reader for javascript and got this:

function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1]; }
}
alert('Query Variable ' + variable + ' not found');
}
var myvar = getQueryVariable("var");

The last line shows how it is called.
But The alert message comes up because it is looking for the actual page's variables. How can I get the script to check for it's own variables.
Thanks,

tech_support
11-11-2007, 09:10 AM
function getQueryString(jsfile, variable) {
var s = document.getElementsByTagName("script");
for (var i=0; i < s.length; i++) {
if (s[i].src == jsfile) {
var vars = query.split("&");
for (var e=0;e<vars.length;i++) {
var pair = vars[e].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return '';
}
}
}
document.write( getQueryVariable("myfile.js","var") );


Untested.

jscheuer1
11-11-2007, 03:10 PM
Tested (credit to mwinter for the RegExp/exec technique):


function getQueryValue(var_name) {
var s = document.getElementsByTagName('script'),
m = (new RegExp('[?&;]' + var_name + '=([^&;#]*)')).exec(s[s.length-1].src);
return m ? unescape(m[1]) : null;
}
alert(getQueryValue('var'))

Notes: I was playing with this and realized that, at the point in time that the document parses the above, the external script that it is in is the last of the bunch on the page, even if there are others after it.

This will not necessarily be the case if execution of checking for the value is delayed, so grab it first thing in the external script. If desired, it can be assigned to a variable for later use in that (and, if set globally, other) script(s), ex:


function getQueryValue(var_name) {
var s = document.getElementsByTagName('script'),
m = (new RegExp('[?&;]' + var_name + '=([^&;#]*)')).exec(s[s.length-1].src);
return m ? unescape(m[1]) : null;
}
var xxx = getQueryValue('var')

This has the advantage of not needing to know the name of the script, which could be changed by the person using it on their page(s).

fileserverdirect
11-12-2007, 11:38 PM
Thanks guys,
I did a little testing myself, Here is my results:
One I found online: Feature not added
tech_support's : Does'nt Work very well
jscheuer1'sKinda Works*
*works in IE\FF, but not in Safari, IE: Mac.
Is it possable to get this script to work cross-browser (ie Works to 100%

Twey
11-13-2007, 12:00 AM
This will not necessarily be the case if execution of checking for the value is delayed, so grab it first thing in the external script. If desired, it can be assigned to a variable for later use in that (and, if set globally, other) script(s), ex:Or perhaps rather:
var getQueryValue = (function() {
var url = document.getElementsByTagName("script");
url = url[url.length - 1].src;

return function(var_name) {
var m = (new RegExp('[?&;]' + var_name + '=([^&;#]*)')).exec(url);

return m ? unescape(m[1]) : null;
};
})();Somewhat neater.

jscheuer1
11-13-2007, 04:46 AM
jscheuer1'sKinda Works*
*works in IE\FF, but not in Safari, IE: Mac.
Is it possable to get this script to work cross-browser (ie Works to 100%

I cannot test code in a browser/on a machine that I don't have. As for IE Mac, almost nothing works in that browser which hasn't been supported by anyone in over 3 years. I did test in Safari 3 Win. Works fine in that. Are you using the most recent Safari Mac? If you go far enough back in the version history of any browser, many scripts will cease working.

In any case, (barring something very unusual) the code will work in any DOM level 2 compliant browser.

The chances that any given browser will respond at that level are increased if the page that the script is on has a valid URL HTML 4.01 DOCTYPE. XHTML DOCTYPEs, HTML DOCTYPEs for versions lower than 4.01 or HTML 4.01 DOCTYPEs without valid URL can all throw some browsers into quirks mode, where virtually anything can happen.

Some tests to try on the 'offending' browsers:


alert(document.getElementsByTagName);


if(document.getElementsByTagName)
alert(document.getElementsByTagName('script').length);

Here is a modified version that might make those other browsers happy:


function getQueryValue(var_name) {
var s = document.documentElement.getElementsByTagName('script'),
m = (new RegExp('[?&;]' + var_name + '=([^&;#]*)')).exec(s[s.length-1].getAttribute('src', 0));

return m ? unescape(m[1]) : null;
}

Also try:


function getQueryValue(var_name) {
var s = document.getElementsByTagName('script'),
m = (new RegExp('[?&;]' + var_name + '=([^&;#]*)')).exec(s[s.length-1].getAttribute('src', 0));

return m ? unescape(m[1]) : null;
}

and:


function getQueryValue(var_name) {
var s = document.documentElement.getElementsByTagName('script'),
m = (new RegExp('[?&;]' + var_name + '=([^&;#]*)')).exec(s[s.length-1].src);

return m ? unescape(m[1]) : null;
}

All of which will also work on level 2 browsers.

I thought of some more things. If it can be determined what about the script that non-supporting browsers don't like, a test for that may be devised and either a fall-back (default) value may be used with them, or a fall-back procedure. Also, if your server supports asp, PHP or any other server side language that supports query 'gets', the query value may be passed to the script using that language for 100% of browsers.

fileserverdirect
11-13-2007, 10:24 PM
Are you using the most recent Safari Mac?
I myself do not own a mac* I was over at another person's house when, being me, Decided to test out my site. And what do ya' know, it does'nt work. I am not In a positon to try out each code, drive 6 miles, find out it doesn't work, drive back 6 miles, try the next one, dive againg 5 miles, and so on.
Opt 1.
I will post all three options on my site, then (is this against DD's rules?) post a topic like "Cross Browser Script testing" and anyone online can test it with any browser.
OPT 2.

I thought of some more things. If it can be determined what about the script that non-supporting browsers don't like, a test for that may be devised and either a fall-back (default) value may be used with them, or a fall-back procedure. Also, if your server supports asp, PHP or any other server side language that supports query 'gets', the query value may be passed to the script using that language for 100% of browsers.
As a matter of fact, my entire website is php. I (in my mind) have already come up with a solution in php. However javascript is still needed, just not the hole query stuff. WHAT I AM TRYING TO DO: O.K., the whole reason for this script is so that one JS file can be used all over my site. the varable that it is retreiving from the url is the root to the main folder. It needs this because it links to a flash document in the main folder. Why do I use Javascript to do this? Because for some odd reason it takes away the dotted border around each flash document and the anyoing "Please Press SPACE to activate or use this control". If you can tell me a way to take away this border from the flash document without using javascript, This topic could be closed, and I can move on with devopment. Thanks in advanced,

jscheuer1
11-13-2007, 10:52 PM
Well, you would still need javascript to get rid of 'click to activate', as it is known (this includes the spacebar thing, it is the same 'feature'). And your script can be PHP powered! What I don't think you realize is (and my PHP is a little weak, so this is just an idea of an example) that you may have an external script tag on your page that looks like this:


<script type="txt/javascript" src="myscript.php?var=some_path">

That much I know for certain. Now how that gets used in the file myscript.php is where I am a little shaky, but it is an ordinary get or some such thing, however that is done in PHP, something like:


var p = <?php echo Get_Query('var') ?>

or maybe like:


<?php
echo 'var p = ' . $_get['var'];
?>

I tell you I'm weak in PHP. Then the script just goes on its merry way, all in javascript, referencing the path from the javascript variable p you just declared.

jscheuer1
11-13-2007, 11:14 PM
OK, I just wanted to see if this was really possible, so I did this:

some.htm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="script.php?var=Hello"></script>
</head>
<body>

</body>
</html>

script.php

<?php
echo "var p = '" . $_GET['var'] . "';\n";
?>
alert(p);

Uploaded to a PHP enabled server, navigating to 'some.htm' got me an alert saying Hello.

Hopefully you can take it from there.

fileserverdirect
11-14-2007, 03:14 AM
O.K. I think I have everything figured out:
mywebsitepage.php:



<?
$root = "../../../";
//some code above
include "logo_insert.php?root=" . $root;
//some code below
?>

logo_insert.php:


<?
$root = $_GET['root'];
echo "<script>\n";
echo "document.write('<the flash stuff>')\n";
echo "document.write('<embed src=\"" . $root . "flash/logo.swf\" attributes...>')";
echo "document.write('<more flash stuff>')\n";
echo "</script>";
?>

Untested
Hope it works.:)
Please reply if you think something is worng;)

jscheuer1
11-14-2007, 04:22 AM
I think you may be missing the point of how much javascript may be almost entirely relied upon in this process, with PHP only used to pass the query string. However, if it works, that's certainly no problem and I'm fairly sure it can be done that way except for one thing. To avoid 'click to activate' and the spacebar thing, the browser must think that the script is external. The way you have it in your post looks to me as though the include is placing the script internally on the page.

If you are having a problem, I'd like a link to an example of the setup you had when you were using my original all javascript solution. That should show me how to adapt it (which I am assuming at least worked in supporting browsers) to use the PHP as a small part of an otherwise all javascript external script.

I think the confusion might be in (because I've seen this before with folks used to includes) not seeing that just because the extension is .php makes no difference, the file may still be used in every way as an external javascript. You seem to want to turn it into an include, but I may be missing something. If I am, never mind.

Twey
11-14-2007, 04:42 AM
You do need to put:
<?php header('Content-Type: text/javascript'); ?>at the top though.

jscheuer1
11-14-2007, 05:18 AM
You do need to put:
<?php header('Content-Type: text/javascript'); ?>at the top though.

Not on the server I tested with my demo. This is a tricky case, as the file is truly a javascript file, and the type attribute was given in the external script tag. I'm not sure if what you are proposing would help at all, perhaps it may even hinder. For DD's getpics.php file, (I'm assuming it's) ddadmin used:


Header("content-type: application/x-javascript");

which obviously 'works', or at least doesn't cause a problem for most applications of the PHP Photo Album script of which it is a part.

Things get more complicated, as we aren't sure really what exactly fileserverdirect is doing, or what results it is producing at this point.

Twey
11-14-2007, 05:29 AM
Not on the server I tested with my demo.It's browser- and mode-dependent, not server-. I think Mozilla in standards mode will not include it if it doesn't have the right MIME type -- it certainly doesn't for CSS.
This is a tricky case, as the file is truly a javascript file, and the type attribute was given in the external script tag.This tells the browser what to expect, and does not override the MIME type of the actual file.
For DD's getpics.php file, (I'm assuming it's) ddadmin used [application/x-javascript]This is a proposed new MIME type for Javascript. I don't think it's fully supported yet, though.

Trinithis
11-14-2007, 05:41 AM
What exactly is a MIME type?

Twey
11-14-2007, 07:04 AM
A MIME type is a string conforming to a standard format that uniquely identifies the type of data being sent (i.e. what sort of parser to use for it).

jscheuer1
11-14-2007, 12:52 PM
It's browser- and mode-dependent, not server-. I think Mozilla in standards mode will not include it if it doesn't have the right MIME type -- it certainly doesn't for CSS.

I had originally tested in FF. I changed my demo's DOCTYPE to strict, it still worked. Remember though, an external javascript file may have the extension .txt - how do you think that is served? As far as I know, an external javascript may have any extension one likes. In this case, the PHP extension simply tells the server to parse it as PHP, working its PHP 'magic' on any parts of it that are coded as PHP.

I think the major difference between an external javascript file and an external css file (where I've seen this mime type issue matter in some browsers) is that a javascript file may be served as text/html, which this will be, and still 'work'. That and the type of tag used. For css, the tag used is a link tag. For javascript, it is a script tag. Although the standard requires the type attribute, browsers all assume this type of tag will deliver text/javascript unless something else is specified.

So, in all likelihood, your original idea wouldn't hurt anything, at least not in theory, and may even be required at some point in the future, but by that time it might be the apx/script header, or a player to be named later.

Twey
11-14-2007, 08:04 PM
I had originally tested in FF. I changed my demo's DOCTYPE to strict, it still worked. Remember though, an external javascript file may have the extension .txt - how do you think that is served?With a correct MIME type, I would hope.
As far as I know, an external javascript may have any extension one likes. In this case, the PHP extension simply tells the server to parse it as PHP, working its PHP 'magic' on any parts of it that are coded as PHP.Yes, it may have any extension one likes. I wasn't talking about extensions.
So, in all likelihood, your original idea wouldn't hurt anything, at least not in theory, and may even be required at some point in the future, but by that time it might be the apx/script header, or a player to be named later.I would suspect that there are browsers that require it. IE as yet doesn't support application/x-javascript (although it performs its usual MIME-type-overriding bugginess). It is, at any rate, simply bad practice to send files with the wrong MIME type, and PHP's default tends to be text/html.

fileserverdirect
11-14-2007, 09:17 PM
First of all thanks guys,
What I am getting out of this conversation is that:

I need an external JS file(php with mime) to get rid of the "click to activate"
I should have a php document with <?php header('Content-Type: text/javascript'); ?> in the top
my document (insert_logo.php) should look some-what like this:


<?
header('Content-Type: text/javascript');
$root = $_GET['root'];
?>
document.write('<the flash stuff>')
document.write('<embed src="<?php echo $root; ?>flash/logo.swf" attributes...>')
document.write('<more flash stuff>')


One question: should I use include... in php, or in html:<script...>?
Thanks,

Twey
11-14-2007, 09:26 PM
<script>.

jscheuer1
11-14-2007, 09:30 PM
Use a script tag:


<script type="text/javascript" src="insert_logo.php?root=whatever"></script>

That mime type header stuff is a bit of a red herring, but shouldn't hurt.

Twey
11-14-2007, 11:00 PM
It's not a red herring, it should be necessary. If it isn't in some browsers, that's probably an error on their part.

fileserverdirect
11-15-2007, 12:15 AM
Thanks Twey, jscheuer1! I will post anymore future problems in this topic, (I will test the idea tomarrow)
But with all this MIME stuff, I had another Idea... New topic because it's kinda un-realted to this topic.
:)THANKS!:)

jscheuer1
11-15-2007, 04:41 AM
Great!

On this mime type thing, Twey - I'm not entirely comfortably with either of our views. I seriously doubt that there is any browser that would require it, though there may be one or two. But that is probably owing to the nature of the script tag and how it is supported, which is with much more leniency than the standards might seem to demand. I'm thinking that being the case though, once a standard begins to be adopted, by that time, it might not be the current one. And that there may even be current or recent browsers that could as easily be thrown off by it.

Twey
11-15-2007, 08:08 AM
And that there may even be current or recent browsers that could as easily be thrown off by it.If there are, they would be equally "thrown off" by standard static .js files (text/javascript is the default MIME type for these on Apache at least).

Use in Web pages aside, it's simply bad practice to serve files with the wrong MIME type. You never know what might be accessing them, or how it might affect them.

jscheuer1
11-15-2007, 03:45 PM
I've been looking into this issue of the header some more, and I am convinced, if for no other reason than, if I view the script file, the one I called script.php, directly in the browser with no header (which of course makes its mime type the default - text/html), I see:


var p = 'Hello';alert(p);

If I add the text/javascript Content header, I get:


var p = 'Hello';
alert(p);

Most of us know that, either will work, but I wrote it to be as it is shown in the second case, and if I had left out the first semicolon (from the javascript part, as can normally be done with javascript in this situation) it wouldn't have.

Twey
11-15-2007, 09:20 PM
It would still work. The line break is still there, it's just that when sent with a text/html MIME type your browser attempts to parse it as HTML, and as we know, HTML ignores line breaks. View the source to see what's really being sent.