Passing JS variables from one function to another

Tenant

New Member
Messages
13
Reaction score
0
Points
0
If i see one person say place the variable outside the functions I am going to slap them. I just read through many forums were that is all they said. I am using Ajax to pull data meaning the data is pulled into a function. I can not place the variables outside it. This is what I need to be able to do.

Code:
function1()
{
 var time = resp.test[0].time;
 var amount = resp.test[0].amount;
 alert(amount);

}

function2(obj)
{
  if (time > 10){
      doument.test.value = amount
 }
}
 

quantum1

New Member
Messages
68
Reaction score
0
Points
0
At the risk of being slapped I will hazard a reply. :O
Question: You want to set the variable "time" in function1 and have the value of that variable available in function2?
 

Spasm

New Member
Messages
10
Reaction score
0
Points
0
Ummm... There isn't any other way to do it besides putting the variable outside the function. :nuts:


Variables declared inside of a function will die when the function exits. These are called local variables, and can only be accessed from inside of that particular function. Local variables can have the same name as each other, but not the same as global variables that already exist.

Variables declared outside all functions in the body of the script will survive from the point they are declared until the script ends. These are called global variables, and can be accessed from inside functions as well as outside.


Code:
var time = 0;

function1()
{
 time = resp.test[0].time;
 var amount = resp.test[0].amount;
 alert(amount);
}

function2(obj)
{
 if (time > 10)
 {
  document.test.value = amount
 }
}



I haven't done any web developing in a while, and I didn't use alot of AJAX when I did, so I may be wrong. I don't understand what you mean by data is being pulled into a function, and you can't declare variables outside of it. This is what should happen:

1. You declare the global variables
2. You call your function
3. Your function sets the global variables
4. Other function can use the global variables later


Type "javascript variable scope" into Google for more info.


PS - There was a typo in function2, "document" was missing the "c". Maybe that was causing problems for you.
 
Last edited:

quantum1

New Member
Messages
68
Reaction score
0
Points
0
another way to pass information back and forth is to store it in session variables....this might work if the function interactions aren't buzzing along at one million calls per second...which with ajax they might
 
Top