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.

Pinkie
  • 10,126
  • 22
  • 78
  • 124
  • I believe this is a duplicate question: http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery – kazinix Oct 20 '11 at 03: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? – nnnnnn Oct 20 '11 at 03: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 – Pinkie Oct 20 '11 at 03:20

8 Answers8

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

Ricardo Tomasi
  • 34,573
  • 2
  • 55
  • 66
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>
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 1
    This is a great and such a simple solution. – Pinkie Oct 20 '11 at 03:35
  • So that is what you actually wanted. Question totally misunderstood it seems by rest. – Birey Oct 20 '11 at 03:39
  • 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. – Pinkie Oct 20 '11 at 03:45
  • 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. – Ricardo Tomasi Oct 20 '11 at 05:33
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

mrtsherman
  • 39,342
  • 23
  • 87
  • 111
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));

});
Birey
  • 1,764
  • 15
  • 20
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);
  }
})();
Pebbl
  • 34,937
  • 6
  • 62
  • 64
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.

Brian Nickel
  • 26,890
  • 5
  • 80
  • 110
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>
kazinix
  • 28,987
  • 33
  • 107
  • 157
-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;
 }
}
James Williams
  • 4,221
  • 1
  • 19
  • 35