0

I've been struggling to convert a JavaScript function to a global variable.

I've got 2 files in total that are basically part of the entire function, here is the JavaScript function.

<script type="text/javascript">
$.get("banner1.php", function(getbannerlink1) {
$("#banner1").load(getbannerlink1+ " #productImage");
// var window.bannerlink1=getbannerlink1; (this doesn't want to work)
});
<script>

Basically banner1.php selects ONE random URL out of an array, and echoes the URL. This JavaScript then gets the URL, and then does a .load() function of that URL and gets the #productImage class from that URL, basically it gets the product image from the random URL. That works all good. Now I need to convert the getbannerlink1 variable to a global variable, because I would like to use the link outside of this function as well.

I've tried using the following just before closing the function:

var window.bannerlink1=getbannerlink1;

but this is just destroying the function altogether :/

What am I doing wrong?

StuyvesantBlue
  • 135
  • 1
  • 15

2 Answers2

2

var window.bannerlink1 is a syntax error. var should only be used with variable identifiers, which may not contain a period.

You want to set a property of window, not declare a new variable name, so just drop the var.

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • Thanks, I've tried this out, and used: document.write(bannerlink1); to output it elsewhere in the same HTML page, but this is returning absolutely no result, the function however is not destroyed now. But the variable seems to be empty for some reason... – StuyvesantBlue Jun 04 '13 at 14:18
  • @user2255785 You are trying to use the value before the callback runs. See **[How to return the response from an AJAX call?](http://stackoverflow.com/q/14220321/710446)** for a full explanation and solutions. – apsillers Jun 04 '13 at 14:23
  • Thank you, all sorted out - I am (obviously) very amateurish. – StuyvesantBlue Jun 04 '13 at 22:10
2

Drop the var

window.bannerlink1 = getbannerlink1; 

Ideally you would avoid using a lot of globals and use a global namespace to hold the values.

epascarello
  • 204,599
  • 20
  • 195
  • 236