5

I have

<script type="text/javascript" src="http://doamin.com/js/whatever.js?ref=images"></script>

Note the ref=images at the end of the url. My questions is, how do i get the ref variable from the url and use it inside this same js file.

3
  • I believe this is a duplicate question: stackoverflow.com/questions/1403888/… Commented Oct 20, 2011 at 3:11
  • Well one way is to use server-side technology to read the request parameter and dynamically inject it into the JS that is served. Is that an option? Commented Oct 20, 2011 at 3:17
  • I'm using php. ref depends on the generated php variable. I want to pass that variable to the js file. Server side is ok with me. I thought the best way to do it is to put it as a url variable at the end of the js file. But i don't know how to access it. Other methods are ok with me Commented Oct 20, 2011 at 3:20

8 Answers 8

3

Simplifying mrtsherman's idea, just find the script with the correct src (from within whatever.js):

var whatever = $('script[src*=http://domain.com/js/whatever.js]')

if (whatever.length){
    var ref = whatever.attr('src').match(/\?ref=(.*)/)
    if (ref && ref[1]){
        ref = ref[1] // ref == 'images'
    }
}

update: since you just want to output something from PHP and use it in your script, you have a much better option:

<script id="whatever" src="http://domain.com/whatever.js" data-ref="images"></script>

Then from your script (assuming jQuery >= 1.4):

var ref = $('#whatever').data('ref') // "images"

This is the recommended and standard way to get data from server-side in your client scripts.

See http://html5doctor.com/html5-custom-data-attributes/ and http://dev.w3.org/html5/spec/elements.html#embedding-custom-non-visible-data

Sign up to request clarification or add additional context in comments.

1 Comment

I did not try this, but also seems like an elegant solution.
2

If whatever.js is a just js file, you can't.

If it is just a request uri and using the server side script to output the javascript content, you can get the variable from the get parameter.

If you want to pass the variable to the whatever.js, you can just define the variable before include whatever.js and then use the variable in whatever.js.

<script type="text/javascript">
<!--// 
  ref = 'images';
//-->
</script>

4 Comments

This is a great and such a simple solution.
So that is what you actually wanted. Question totally misunderstood it seems by rest.
Yes that's it. We have many correct answers on here. This one wins for it's flexibility. After i set ref with php, any js file on the page will be able to read it now.
Note that this will pollute the global scope, you might want to pick a more specific variable name, or add it as a property of another object to avoid clashes.
1

I don't know of a way to get the src attribute for only the current blocks script element. But you could get all scripts on the page and then parse them.

//untested
var scripts = $('script[src]');
//loop through scripts and somehow identify the one that is yours
for (var script in scripts) {
  if (myscript) {
    var refvalue = getRef($(script).attr('src'), 'ref');
  }
}

//gup the parameter
function getRef(url, name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

Hopefully this is enough to go on

Comments

1

try this http://jsfiddle.net/fnE6w/

$("script[src*='ref=']").each(function(){
    var src=$(this).attr("src");
    var start=src.indexOf("ref=");
    var end=-1;


    if(start>0)
        end = src.indexOf("&",start+4);
    if(end==-1) end=src.length-1;    
    alert(src.substring(start+4,end));

});

Comments

0

I seem to remember there being a way to get the calling script tag in some browsers but I can't find reference to it.

The next best thing is to follow something like this: http://snipplr.com/view/354/

You could search for the script tag with a source you like and then extract the string. Be careful! If you set this value based on user input your user could inject a query string that your scanner could misinterpret, creating a risk. The same kind of paranoid URL parsing approach used for regular query string should be used for this.

Comments

0

Your problem here is, you cannot get the query from the URL of the script:

<script src="http://doamin.com/js/whatever.js?ref=images">
     //Want to get the query here, but you can't
</script>

You said:

I'm using php. ref depends on the generated php variable. I want to pass that variable to the js file. Server side is ok with me. I thought the best way to do it is to put it as a url variable at the end of the js file. But i don't know how to access it. Other methods are ok with me

Let's go back to your purpose, to pass a php variable to the script... Why not pass the php variable to the php page containing the script? Then get it using scripts provided by other posters here. Your URL to PHP page containing the script:

http://domain.com/ThePHPPageContainingTheScript.php?ref=images

Then this page contains the script:

<script src="http://doamin.com/js/whatever.js">
     //Get the query from window.location, it's possible!
</script>

Comments

0

Just in case it is useful to anyone out there searching for something similar to this, here is an example of one way to send larger amounts of data to a script without the use of AJAX.

<script src="test.js" name="testjs">
{
  "here"    : "is",
  "another" : "way",
  "of"      : "passing",
  "larger"  : "amounts",
  "of"      : "data",
  "to"      : "a script"
}
</script>

Then in your external test.js script you just need the following:

(function(){
  var script = document.scripts.namedItem('testjs'), obj, data;
  if ( script && (data = script.innerHTML) ) {
    if ( typeof JSON != 'undefined' ) {
      obj = JSON.parse(data);
    }
    else if ( typeof jQuery != 'undefined' ){
      obj = jQuery.parseJSON(data);
    }
    /// obj now contains the object representation of your data
    alert(obj);
  }
})();

Comments

-1

You will need code similar to the following. This gets everything after the ? and seperates it into basically key/pairs array.

var GETDATA = new Array();

// Get the string that follows the "?" in the window's location.
var sGet = window.location.search;
if (sGet) // if has a value...
{
 // Drop the leading "?"
 sGet = sGet.substr(1);

 // Generate a string array of the name value pairs.
 // Each array element will have the form "foo=bar"
 var sNVPairs = sGet.split("&");

 // Now, for each name-value pair, we need to extract
 // the name and value.
 for (var i = 0; i < sNVPairs.length; i++)
 {
  // So, sNVPairs[i] contains the current element...
  // Split it at the equals sign.
  var sNV = sNVPairs[i].split("=");

  // Assign the pair to the GETDATA array.
  var sName = sNV[0];
  var sValue = sNV[1];
  GETDATA[sName] = sValue;
 }
}

4 Comments

NOTE: This mainly works for html or php pages with the ?var=foo declaration
You won't be dealing with location.search in this case.
This won't work. window.location applies to where the page comes from, not where included script files come from. Even if you put that code inside the JS script file it will still be dealing with the current page URL.
that is why I added my not in the comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.