Getting Globally declared variable value from 1 function to another function - javascript

I have a very common question about javascript
i have a globally declared variable but how can a function with that variable pass the value in the globally declared variable then use it in the second function??
var ID;
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
ID = this["ID"]
alert(ID);
}
})
}
function test1() {
$.getJSON("/TestSite?Test=" + ID; )
}
alert(ID);
test();
test1();
Function test alert the ID but when i declare it Globally it was undeclared.
Can someone help me with this??
Thanks

I think you are expecting getJSON to be synchronous, but it is not. If the calls are dependent you should nest them:
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
ID = this["ID"]
$.getJSON("/TestSite?Test=" + ID; )
})
})
}
test1 is being called before test has completed its getJSON call

Because getJSON is asynchronous, the proper way do perform what you need is to use the returned ID in the callback of getJSON:
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
var theId = this["ID"];
alert(theId);
test1(theId);
}
});
}
function test1(id) {
$.getJSON("/TestSite?Test=" + id);
}
test();

Try this first you set you id to Zero
var ID =0;

Related

javascript function execute after a variable got value

Can function be executed after some variable got value (or changed) in JavaScript?
In my example, the variable is hoisted at first which is declared to be a global, then will assign some value to it in getData() function.
I have tried using .delay() method, but i don't know how much time the ajax needs.
briefly describe:
1) Declaring variable
2) calling getData() function, then assign the data to variable
3) calling funcA() function
4) calling funcB() function and pass function doSomething() as a callback in funcA()
5) calling the callback function in funcB()
6) log the data in doSomething()
<script>
var variable;
variable = getData();
funcA();
function funcA() {
funcB(doSomething);
function doSomething(data) {
console.log(data);
}
}
function funcB(callback) {
if (variable !== undefined) {//it is obviously undefined.
callback(variable);
}
}
</script>
//another js file
<script>
function getData() {
//get data by using ajax
//i don't know how much time it needs.
return data;
}
</script>
change your getdata to this:
function getData() {
$.ajax({
url: "some url",
success: function(result){
variable = result;
//do everything that should be done here or call your callback
});
}

Pass a function as a parameter that may not exist yet in Javascript

Is it possible to pass a callback function that does not exist yet? My goal is to have a common function that will wait for another callback function to exist, when it does exist, it should execute it. This is what I have so far, but I can't figure out how to pass the function in that doesn't exist as a function yet.
function RunTemplateFunction(callback, userInfo) {
if ($.isFunction(callback)) {
callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(callback)) {
clearInterval(myInterval);
callback(userInfo);
}
}, 200);
}
}
I run the function like this:
RunTemplateFunction(MyFunctionToRun, GetUserInfo());
I get MyFunctionToRun is undefined for obvious reasons, I also tried the workaround of passing the function as a string and then convert the string to a function using eval(). But that throws the same error. I also thought of using the new function(), but that actually creates a new function.
Any help is appreciated. thank you.
If you call RunTemplateFunction by undefined there is no way we can see, is callback is defined or not, as we don't have reference to anything.
If you can modify the declaration to accept object as below, we can achieve what we want
function RunTemplateFunction(options, userInfo) {
if ($.isFunction(options.callback)) {
console.log('called1',userInfo);
options.callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(options.callback)) {
console.log('Called dynamically!!');
clearInterval(myInterval);
options.callback(userInfo);
}
}, 200);
}
}
var options = {}
RunTemplateFunction(options,{user:122});
options.callback = function(){
console.log("I'm called!!");
}
This will print
Called dynamically!!
I'm called!!
EDIT:
We can also call callback function in following way without setInterval, it will look different but options.callback variable is replaced by template.callMe function and its instantaneous also.
function TemplateRunner(userInfo){
this.callMe = function(cb){
this.templateFunction(cb);
}
this.templateFunction = function(callback){
callback(userInfo);
}
}
var template = new TemplateRunner({user:100})
template.callMe(function(user){
console.log('call me1',user);
});
template.callMe(function(user){
console.log('call me2',user);
})
This will print
call me1 {user: 100}
call me2 {user: 100}

How can I pass a value to a javascript function?

I have a function like this:
retrieveData();
and then javascript code like this:
var retrieveData = function ()
{
function () { $('#updater').show(); }
$.post('......
This is I think a simple question but how can I pass an argument to the retrieveData function and have it availabe for use in the code following the .post ?
Simply
var retrieveData = function (a) {
$.post(...);
// use `a` here
}
retrieveData("some value");
var retrieveData = function (answer) {
$.post('The answer is ' + answer);
}
retrieveData(42);

return vs. callback in a Javascript function

Say I write this function...
var sayHi = function() {
return "hi";
}
alert(sayHi()); will return "hi".
Now if I write it this way...
var sayHi = function(callback) {
callback("hi");
}
How do I display "hi" with this function?
Based on an example here: http://nowjs.com/doc
You pass a function to sayHi, so I imagine this:
sayHi(alert);
you must have defined some callback function or pass a anonymous function:
var sayHi = function(callback) {
callback("hi");
}
sayHi(function(message){
alert(message);
});
Try this:
sayHi(function(msg){
alert(msg)
});
Your new sayHi function doesn't return a value, so you have to perform the alert in the callback function.
sayHi(function(value) {
alert(value);
});
sayHi(function(msg) {
alert(msg);
});
You have to invert your thinking process when using callbacks. Instead of writing the next operation first, you write the next operation last.
Here in example callback is a function. So you should pass function argument.
You may do this in 2 ways:
var some_fun = function(some_str) {
alert(some_str);
}
var sayHi = function(callback) {
callback("hi");
}
sayHi(some_fun)
or you can pass function when you call it:
var sayHi = function(callback) {
callback("hi");
}
sayHi(function(some_str){
alert(some_str);
});

jQuery plugin public method/function

I am trying to achieve something like the following but dont know whats wrong:
$.a = function() {
// some logic here
function abc(id) {
alert('test'+id);
}
}
$.a.abc('1');
I tried using the return function, but that doesnt seem to work either. Can someone please help.
Thank you for your time.
Since $.a must be a function in itself, you'll have to add the abc function as a property to the $.a function:
$.a = function () {
// some logic here...
};
$.a.abc = function (id) {
alert('test' + id);
};
If abc must be defined from within the $.a function, you can do the following. Do note that $.a.abc will not be available until $.a has been called when using this method! Nothing inside a function is evaluated until a function is called.
$.a = function () {
// Do some logic here...
// Add abc as a property to the currently calling function ($.a)
arguments.callee.abc = function (id) {
alert('test' + id);
};
};
$.a();
$.a.abc('1');
$.a = (function(){
var a = function() {
//...
};
a.abc = function() {
//...
}
return a;
})();

Categories

Resources