473,804 Members | 2,536 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

global var javascript

3 New Member
I think the below code should work, but for some reason the setNumbers variable isn't keeping its value after the function. I thought if I declared variables outside of any function they would behave globally, so if I put data into them in a function it would carry over out of the function. Where the alert is at the bottom works, but if its moved one block lower it gives me an undefined. All the var's are delcared in the main part of code. Can someone tell me what I'm doing wrong?


Expand|Select|Wrap|Line Numbers
  1. var setNum = 0;
  2. var imageArray = new Array();
  3. var srcArray = new Array();
  4. var altArray = new Array();
  5. var imageSet = new Array(); /////Declared Here outside of any function
  6. var setNumbers;
  7. var numXml;
  8. var xDocument;
  9. var xmlDoc;
  10. var counter=0;
  11. var cnt = 0;
  12.  
  13.     var URL = "pictures.xml";
  14.     var request = false;
  15.     if (window.XMLHttpRequest) {
  16.         request = new XMLHttpRequest();
  17.     } else if (window.ActiveXObject) {
  18.         try {
  19.             request = new ActiveXObject("Msxml2.XMLHTTP");
  20.         } catch (e) {
  21.             try{
  22.                 request = new ActiveXObject("Microsoft.XMLHTTP");
  23.             } catch (e){}
  24.         }
  25.     }
  26.     request.open("GET", URL, true);
  27.     request.onreadystatechange = function() {
  28.         if (request.readyState == 4 && request.status == 200) { 
  29.             xmlDoc = request.responseXML;
  30.             xDocument=xmlDoc.getElementsByTagName("picture");
  31.             numXml = xDocument.length;
  32.             setNumbers = numXml / 4;
  33.  
  34.             for (i=0;i<numXml;i++){
  35.                 srcArray[i] = xmlDoc.getElementsByTagName("src")[i].firstChild.nodeValue;
  36.                 altArray[i] = xmlDoc.getElementsByTagName("alt")[i].firstChild.nodeValue;
  37.                 var img = "<img src=\'"+srcArray[i]+"\' onClick=\'replaceMain("+i+")\' onmouseover=\"this.style.cursor=\'pointer\'\" alt=\'"+altArray[i]+"\' width=144 height=108 >";
  38.                 imageArray[i] = "<li>"+img+"</li>";
  39.  
  40.                 } 
  41. //calls function fisherYates and puts new data into groups for display
  42. fisherYates(imageArray);                        
  43. while(counter < setNumbers) {
  44.     imageSet[counter]=imageArray[cnt];
  45.     cnt++;
  46.     imageSet[counter]+=imageArray[cnt];
  47.     cnt++;
  48.     imageSet[counter]+=imageArray[cnt];
  49.     cnt++;
  50.     imageSet[counter]+=imageArray[cnt];
  51.     cnt++;
  52.     counter++;
  53. }
  54. alert(imageSet[2]); ///////////works here
  55. }
  56. alert(imageSet[2]); /////////doesn't work says "undefined"
  57. }
  58.     request.send(null);
Feb 29 '08 #1
2 2002
mrhoo
428 Contributor
The first alert fires before the xmlResponse returns a value (or doesn't), the second one after.

Put some code in the loop and look at the headers and text of the xmlHTTPRequest object.
Mar 1 '08 #2
hsriat
1,654 Recognized Expert Top Contributor
I think that the problem is being caused, because AJAX is asynchronous.

So what ever you are doing after sending AJAX request, you may delay the function that needs to manipulate the response text when you are using global variables.
Like this...
Expand|Select|Wrap|Line Numbers
  1. function doAfterAjaxResponds() {
  2.    if (setNumbers=="") {//YOUR GLOBAL VARIABLE CONTAINING RESPONSE
  3.  
  4.       //KEEP CHECKING EVERY 1/10 SEC IF AJAX RESPONDED 
  5.       wait = setTimeout("doAfterAjaxResponds()", 100);
  6.    }
  7.    else {
  8.  
  9.       //DO WHATEVER YOU HAVE TO DO WITH THE RESPONSE TEXT
  10.  
  11.    }
  12. }
Mar 1 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

4
24189
by: Andrew V. Romero | last post by:
I have been working on a function which makes it easier for me to pull variables from the URL. So far I have: <script language="JavaScript"> var variablesInUrl; var vArray = new Array(); function loadUrlVariables() { varString = location.search;
8
2561
by: lawrence | last post by:
I'm learning Javascript. I downloaded a script for study. Please tell me how the variable "loop" can have scope in the first function when it is altered in the second function? It is not defined in global space, therefore it is not a global variable, yes? Even if it was global, how would it get from one function to another? In PHP variables are copied by value. Are they copied by reference in Javascript? <SCRIPT LANGUAGE="JavaScript">
1
1456
by: Robert North | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I've just started programming JS, and one question keeps nagging me: I can insert a <script> element anywhere in HTML, and when it's executed some DOM objects are created, and placed in the global scope of the script object. But which ones are placed in the global scope?
6
3951
by: Soha | last post by:
I'm a beginner in using javascript and i need a reply so urgent; i have a problem in using javascript with asp the problem is that i want to define a global variable and then change the value of it after clicking on a link which activate a function that changes the global variable. this variable i use as the value of a hidden field in a form. my problem is that the global variable dosen't change. this is the code i used to do this: ...
6
1956
by: Bruce | last post by:
Can anyone tell me why this doesn't work? My end goal here is to be able to write Javascript library modules that can be used by both client and server side code. My test here consists of 2 files: testGlobal.asp : <%@LANGUAGE="JAVASCRIPT" CODEPAGE="1252"%> <script language="JavaScript" type="text/javascript" runat="server"
16
3237
by: Roman Ziak | last post by:
Hello, there were times when I used to be looking for a way to access JavaScript Global object similar to those found in VBScript or PHP ($GLOBALS). At present this has only academic value for me. I was doing research on JavaScript inheritance recently (simplifying it in particular) and after reading 10.1.1, 10.1.3 and some other sections of ECMA262 I got a hint on accessing global object from different than global scope.
0
2483
by: hynek.cihlar | last post by:
A strange behaviour thatI found in ASP.NET 2.0. I am trying to issue a callback request (handled by ICallbackEventHandler and RaiseCallbackEvent) and a regular GET request in the client browser and handle them at the same time - in parallel. The funny thing is that the behaviour of the implementation I created depends on the existence of Global.asax in the Web application. Here is the source of the page that handles the regular GET...
3
2777
by: User1014 | last post by:
A global variable is really just a property of the "Global Object", so what does that make a function defined in the global context? A method of the Global Object? http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Defining_Functions doesn't actually give any insight.
15
2059
by: Bob | last post by:
Is there anyway to access the global object from inside a function other than doing a "var _global = this;" before declaring the function? Thanks
27
1704
by: Erwin Moller | last post by:
Hi group, Consider this simple script (tested on FF3): <script type="text/javascript"> test = 'outer'; for (var i=0;i<2;i++){ alert(test); var test = 'inner'; alert (test);
0
9711
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9591
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10087
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9166
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7631
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5529
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.