Page 1 of 3 123 LastLast
Results 1 to 10 of 27

Thread: JS file reading its own query strings

  1. #1
    Join Date
    Nov 2006
    Location
    Northeast USA
    Posts
    408
    Thanks
    8
    Thanked 30 Times in 28 Posts

    Question JS file reading its own query strings

    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:
    Code:
    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,
    -Ben -- THE DYNAMIC DRIVERS
    My Links: My DD Profile||My Youtube Video Tutorials||DD Helping Coders||DD Coders In Training
    I told my client to press F5, the client pressed F, then 5, *facepalm*

  2. #2
    Join Date
    May 2006
    Location
    Sydney, Australia - Near the coast.
    Posts
    1,995
    Thanks
    0
    Thanked 8 Times in 7 Posts

    Default

    Code:
    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.
    Peter - alotofstuffhere[dot]com - Email Me - Donate via PayPal - Got spare hardware? Donate 'em to me :) Just send me a PM.
    Currently: enjoying the early holidays :)
    Read before posting: FAQ | What you CAN'T do with JavaScript | Form Rules | Thread Title Naming Guide

  3. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Tested (credit to mwinter for the RegExp/exec technique):

    Code:
    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:

    Code:
    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).
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  4. #4
    Join Date
    Nov 2006
    Location
    Northeast USA
    Posts
    408
    Thanks
    8
    Thanked 30 Times in 28 Posts

    Default

    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%
    -Ben -- THE DYNAMIC DRIVERS
    My Links: My DD Profile||My Youtube Video Tutorials||DD Helping Coders||DD Coders In Training
    I told my client to press F5, the client pressed F, then 5, *facepalm*

  5. #5
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    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:
    Code:
    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.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Quote Originally Posted by fileserverdirect View Post
    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:

    Code:
    alert(document.getElementsByTagName);
    Code:
    if(document.getElementsByTagName)
    alert(document.getElementsByTagName('script').length);
    Here is a modified version that might make those other browsers happy:

    Code:
    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:

    Code:
    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:

    Code:
    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.

    Edit: 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.
    Last edited by jscheuer1; 11-13-2007 at 05:15 AM. Reason: add info
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #7
    Join Date
    Nov 2006
    Location
    Northeast USA
    Posts
    408
    Thanks
    8
    Thanked 30 Times in 28 Posts

    Default

    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,
    -Ben -- THE DYNAMIC DRIVERS
    My Links: My DD Profile||My Youtube Video Tutorials||DD Helping Coders||DD Coders In Training
    I told my client to press F5, the client pressed F, then 5, *facepalm*

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    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:

    Code:
    <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:

    Code:
    var p = <?php echo Get_Query('var') ?>
    or maybe like:

    PHP Code:
    <?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.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  9. #9
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    OK, I just wanted to see if this was really possible, so I did this:

    some.htm
    Code:
    <!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
    Code:
    <?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.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  10. #10
    Join Date
    Nov 2006
    Location
    Northeast USA
    Posts
    408
    Thanks
    8
    Thanked 30 Times in 28 Posts

    Default

    O.K. I think I have everything figured out:
    mywebsitepage.php:

    PHP Code:
    <?
    $root 
    "../../../";
    //some code above
    include "logo_insert.php?root=" $root;
    //some code below
    ?>
    logo_insert.php:
    PHP Code:
    <?
    $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
    Last edited by fileserverdirect; 11-14-2007 at 03:17 AM. Reason: syntax error
    -Ben -- THE DYNAMIC DRIVERS
    My Links: My DD Profile||My Youtube Video Tutorials||DD Helping Coders||DD Coders In Training
    I told my client to press F5, the client pressed F, then 5, *facepalm*

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •