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?

2 Answers 2

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.

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

3 Comments

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...
@user2255785 You are trying to use the value before the callback runs. See How to return the response from an AJAX call? for a full explanation and solutions.
Thank you, all sorted out - I am (obviously) very amateurish.
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.

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.