How can I start using variable outside $.get() function? - javascript

var userIdD = $.get('http://someurl.com/options.php', function(abc) {
var abc = $(abc);
var link = $(abc).find('a:contains(View My Profile)');
//console.log (link);
var userID = $(link).attr('href');
var userId = $(userID);
console.log(userId);
console.log(userID);
});
console.log(userIdD);
console.log(userId);
I can`t start using variables "userIdD" & "userId" outside function "abc".
Inside it, it works greatly.
Can someone help me to use them outside it? where I'm wrong?

Declare your variables outside the function:
var userID, userId;
var userIdD = $.get('http://someurl.com/options.php', function(abc) {
var abc = $(abc)
var link = $(abc).find('a:contains(View My Profile)')
//console.log (link)
userID = $(link).attr('href');
userId = $(userID)
console.log(userId)
console.log(userID)
})
console.log(userIdD)
console.log(userId)

The problem is that userIdD is set asynchronously. The stuff that happens inside the function call happens after the stuff outside the function call.
Here's a simplified example which you can run:
$.get('http://jsonplaceholder.typicode.com', function(){
alert('Stuff inside function happening');
});
alert('Stuff outside function happening');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now, if we look at your code, we'll see that you're trying to console.log variables that are set inside the function call.
To go around the asynchronicity, you can make use of promises. Let's have a look at how that works...
var valuesPromise = $.get('http://jsonplaceholder.typicode.com').then(function(serverResponse){
return { objectId: 123 }; // return stuff you want to use later
});
// later in your code, you can make use of the returned value...
valuesPromise.then(function(returnedValue){
alert(returnedValue.objectId); // alerts '123'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

How to make a js var in a function global to use it outside?

I want to make the "var id" in the function global. That i can use the value of it in the alert outside the function. Thats my code:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
}
alert(id);
</script>
You didn't specified what is your final goal or why are you trying to move id to a global scope, but you can do it by simple moving the var id (declaration) outside the function, then it will be global and accessible by all functions.
Obviously, the alert will show "undefined" since id only gets some value when the myFunctionGetCode() is called.
The code below shows this.
var id;
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
id = con+code;
console.log(id)
}
alert(id);
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
BUT if you want to throw the alert with the id value only when it gets some value then you should move the alert() inside the function. (You can still declare the id variable outside the function to let it global, or inside the function, as you currently have)
Open snippet to see:
//var id; -> You can still declare it here (as global)
function myFunctionGetCode() {
var code = getInputVal('code');
var con = "/";
var id = con+code; //or you can declare it here, but not global
alert(id);
}
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
From your sample code I guess that you do not want to make your value global, but that you want to return a value - after all you are doing an operation inside your function that calculates a value from certain inputs.
So you would use the return keyword, and call the function to get the value:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
return id;
}
alert(myFunctionGetCode());
</script>
As a rule you do not want to make function variables global, since this means the value can be changed anywhere in your script or website, and that might lead to side effects and unexpected values in your function. If you need to pass something in use function parameters (or read from a text input like in your case), if you want to give back a result use return.
Can you move the alert inside the function or return the "id" value from the function instead?
You can make the variable global by doing something like:
window.your_namespace.id = value;
and then access the variable in the same way:
value = window.your_namespace.id
but its best not to pass data around using the global namespace.
You have to make var id to property of window object then you can access the id out side the function.
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
window.id = 10;// Change to this
}
myFunctionGetCode();
alert(id);

Use value from method in javascript object to use in setTimeout function

I have tried different things but I do seem to be looking something over that is too obvious. Trying to use the value a function(method) returns inside an object and use it in another method with setTimeout within that same object.
This is the html:
<h1>3000</h1>
The javascript (jQuery in this case):
var foo = {
getValue: function() {
var h1Text = $('h1').text();
h1Text = parseInt(h1Text);
return h1Text;
},
useValue: function() {
var time = this.getValue();
var alertIt = alert('Hello');
setTimeout(alertIt,time);
}
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));
The alert does show up, but on load rather than using those 3 seconds.
It does log the correct value and also says it's a number so I'm really not sure what I am doing wrong. Any help is appreciated. Thanks
In useValue() you call alert('Hello'), so it's executed immediately and the result is stored in alertIt variable. You should put it inside the function like this, as setTimeout expects a function as a first parameter:
var alertIt = function() {
alert('Hello');
}
setTimeout(alertIt,time);
setTiimeout expects function and not variable.
Also var alertIt = alert('Hello'); this will return undefined.
Note: var a = function() will call it and assign return value. To assign a function to a variable with parameter, use .bind
Try alert.bind(null, "hello");
For demo purpose, I have hardcoded value of delay and commented getValue code.
var foo = {
getValue: function() {
//var h1Text = $('h1').text();
//h1Text = parseInt(h1Text);
return true// h1Text;
},
useValue: function() {
var time = 3000//this.getValue();
var alertIt = alert.bind(null,'Hello');
setTimeout(alertIt, time);
}
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));

How to dynamically change the contents of a function using JavaScript

To help understand this the function is in the html page and it is generated, I cannot change the generated code:
function Update_qu7260() {
var newVal = ''
for( var idx = 0; idx < 2; idx++ )
{
var test
if( idx == 0 ) test = text7263
else if( idx == 1 ) test = text7265
if( test.matchObj ) newVal += test.leftSel + "-" + test.matchObj.rightSel + ","
}
newVal = newVal.substring( 0, newVal.length-1 )
VarQuestion_0001.set( newVal )
qu7260.hasBeenProcessed=false;
doImmFeedback('qu7260');
}
var qu7260 = new Object();
...
qu7260.updFunc = Update_qu7260;
var qObj=[qu7260];
Note in the above the number "7260", the numbers start at 1 so there are lots of them and each Update_###() will be different so I cannot re-write them with "hard wired" code. My code is in an external JavaScript file and is executed onLoad:
...
var updFunc = qObj[0].updFunc.toString();
if(updFunc.indexOf('doImmFeedback(')!=-1){
updFunc = updFunc.replace('doImmFeedback','doImmQuestionFeedback'); // do my function
updFunc = updFunc.replace('function ',''); // remove the word function
var funcName = updFunc.substr(0,updFunc.indexOf('(')); // get the function name e.g. Update_qu7260
updFunc = "window['" + funcName + "']=function" + updFunc.replace(funcName,'');
eval(updFunc);
}
...
When I change the eval() to alert() I can see the that it's correct, however, the eval() is not raising any errors and my function doImmQuestionFeedback is not being called. When I subsequently do an alert(qObj[0].updFunc.toString()) I see the original function.
It would seem that I have provided information that is too complex, so the following code is a better example:
function hi(){alert('hi');}
function changeHi(){
hi(); // I get an alert box with hi
newHi = "function hi(){alert('hi there');}"
eval(newHi);
hi(); // I get an alert box with hi
window.setTimeout('hi()',500); // I get an alert box with hi
}
window.setTimeout('changeHi()',500);
The following is the original question:
I have a predefined function that I did not create, however, I know it's name so I can get the function itself and then I change it by doing:
var funcText = window.updateFunc.toString();
funcText = funcText.replace('doSomeOtherFunction(','doMyFunction(');
How do I update the actual function so it will do all that it did before except it will now call doMyFuntion()?
The following is an example to help visualize what I want to do, the actual function I need to change is very complex. I have:
function updateFunc(whatToUpdate,true){
... - do lots of stuff.
var retVal = doSomeOtherFunction(whatToUdate);
... - do lots of stuff based on retVal
}
I need to change this to:
function updateFunc(whatToUpdate,true){
... - do lots of stuff
var retVal = doMyFunction(whatToUdate);
... - do lots of stuff based on retVal, I have had a chance to change retVal
}
Then the first thing my function will do is call doSomeOtherFunction() check/change the returned value and subsequently return the value to the updateFunc().
I have tried to manipulate the funcText above to:
funcText = 'window.updateFunc = function(...';
eval(funcText);
Without success.
This may be closed enough to what you are looking for.
Assuming you have this original function:
function originalFunc(val) {
// this function converts input string to upper case
return val.toUpperCase();
}
Now you want to override it to something either before or after you execute that function (in this example, we execute before, of course before or after doesn't matter in this case).
// we preserve orignal function
var originalFunc_save = originalFunc;
// now we override the original function with this block
var originalFunc = function(text) {
// lets call the orignal function
text = originalFunc_save(text);
// now do our custom thing
return text.split('').reverse().join('');
}
So our test should work.
var text = 'This is a test';
console.log(originalFunc(text));
Output:
TSET A SI SIHT
This method also works if you have to override functions inside a class. The only thing we have to be careful of is to choose a saved name that doesn't interfere with the original class code. _save may not be good enough, but you get the idea.
UPDATE: I'm updating this code above to use a string variable pointing to the original function. I think this is what the OP wanted.
Original code which defined by some library
function originalFunc(val) {
// this function converts input string to upper case
return val.toUpperCase();
}
Now we use the func string variable to point to that function and execute it.
var text = 'This is a test';
var func = 'originalFunc';
text = window[func](text);
console.log(text);
Output: Of course we get the original intended result because we haven't overridden it.
THIS IS A TEST
Now we write our code to override the original function behavior using a string pointing to the function.
// let's define a new function string
var funcSaved = func + '___saved';
// now preserve the original function code
window[funcSaved] = window[func];
// override the original function code block
window[func] = function(text) {
// lets call the orignal function
text = window[funcSaved](text);
// now do our custom thing
return text.split('').reverse().join('');
}
// let's test the code
text = 'This is a test';
text = window[func](text);
console.log(text);
Output:
TSET A SI SIHT
You can make a clone of updateFunc function, edit it at your discretion and work with it in what follows.
function updateFunc(whatToUpdate, param){ // the initial function
...
var retVal = doSomeOtherFunction(whatToUpdate);
return retVal;
}
// formation of unnamed function as string
var newfunc = updateFunc.toString().replace('function updateFunc', 'function ').replace('doSomeOtherFunction(', 'doMyFunction(');
function doMyFunction(whatToUpdate){ // your new function, just for example
console.log(parseInt(whatToUpdate) * 10);
}
var newUpdateFunc;
// declaring new version of 'updateFunc' function
// which is stored in 'newUpdateFunc' variable
eval("newUpdateFunc = " + newfunc);
newUpdateFunc(3); // outputs '30'
I believe this is a valid use case for the forgotten JavaScript with feature.
Basic idea: you call original updateFunc supplying your own version of doSomeOtherFunction to it using with namespace injection:
function updateFunc(whatToUpdate,true){
... - do lots of stuff.
var retVal = doSomeOtherFunction(whatToUdate);
... - do lots of stuff based on retVal
}
function patchUpdateFunc() {
var original_doSomeOtherFunction = window.doSomeOtherFunction;
var original_updateFunc = window.updateFunc;
function doMyFunction() {
// call original_doSomeOtherFunction() here,
// do your own stuff here.
};
window.updateFunc = function() {
with ({doSomeOtherFunction: doMyFunction}) {
return original_updateFunc.apply(this, arguments);
}
}
}
patchUpdateFunc();
I think you are going at this way too complicated.
If you only have doMyFunction and doSomeOtherFunction to switch between, you could just create a flag somewhere telling you to use one or the other when used in an if-statement.
If you want to call a function with a name you do not know beforehand and you only get a name during runtime, you could either accept the function to call as a parameter or accept the name of the function as a parameter and call it like so: var retVal = window[functionName](); (assuming functionName is a property of the window object).
I would highly recommend directly accepting a function as a parameter since the function may not be defined in a global scope.
EDIT:
After your clarification, I think, I can give you a satisfying answer:
if you have a string like var functionString = "function updateFunc(whatToUpdate){var retVal = doMyFunction(whatToUpdate);}";
You can define a function using a Function object:
window.updateFunc = new Function("whatToUpdate", "return (" + functionString + ")(whatToUpdate)");
This will replace the already existing function and you can give it any valid function string you want as long as you know and specify the arguments.
If I understood correctly, you want to override the external function. You can achieve that with the following code
//Someone else's function
function externalFunction(foo){
return "some text";
}
//Your function
function myFunction(value){
//Do something
}
//Override
var externalFunction = (function(){
var original = externalFunction; //Save original function
return function(){
var externalFunctionReturnValue = original.apply(this, arguments);
return myFunction(externalFunctionReturnValue);
}
})();
I strongly sugest not to use eval, but since you want to parse javascript from string:
function hi(){alert('hi');}
function changedHi(){
hi(); // I get an alert box with hi
newHi = "window['hi'] = function(){alert('hi there');}"
eval(newHi);
hi(); // I get an alert box with hi there
window.setTimeout('hi()',500); // I get an alert box with hi there
}
window.setTimeout('changedHi()',500);
UPDATE:
This code snippet works which is your original code:
<script type="text/javascript">
function doImmFeedback(foo){
console.log("DoImmFeedback: " + foo);
}
function Update_qu7260() {
console.log("Some code")
doImmFeedback('qu7260');
}
</script>
<script type="text/javascript">
var qu7260 = new Object();
qu7260.updFunc = Update_qu7260;
var qObj=[qu7260];
var updFunc = qObj[0].updFunc.toString();
if(updFunc.indexOf('doImmFeedback(')!=-1){
updFunc = updFunc.replace('doImmFeedback','doImmQuestionFeedback'); // do my function
updFunc = updFunc.replace('function ',''); // remove the word function
var funcName = updFunc.substr(0,updFunc.indexOf('(')); // get the function name e.g. Update_qu7260
updFunc = "window['" + funcName + "']=function" + updFunc.replace(funcName,'');
console.log(updFunc);
eval(updFunc);
}
function doImmQuestionFeedback(foo){
//Your function
console.log("doImmQuestionFeedback: " + foo);
}
Update_qu7260(); //This executes your doImmQuestionFeedback
</script>
So if your function isn't running, your function isn't in the global scope, or something else is happening, and we can't know if don't have any more info. Check your developer's console for javascript errors.

Passing a variable from a callback function to another function?

I am working on setting up an HTML5 GeoLocation script and I would like to store the zip code in a cookie but for now I am just trying to figure out how to pass the zip code variable into another function.
Here is my script to reverse geo-code based on lat/long:
function retrieve_zip(callback)
{
try { if(!google) { google = 0; } } catch(err) { google = 0; } // Stupid Exceptions
if(navigator.geolocation) // FireFox/HTML5 GeoLocation
{
navigator.geolocation.getCurrentPosition(function(position)
{
zip_from_latlng(position.coords.latitude,position.coords.longitude,callback);
});
}
else if(google && google.gears) // Google Gears GeoLocation
{
var geloc = google.gears.factory.create('beta.geolocation');
geloc.getPermission();
geloc.getCurrentPosition(function(position)
{
zip_from_latlng(position.latitude,position.longitude,callback);
},function(err){});
}
}
function zip_from_latlng(latitude,longitude,callback)
{
// Setup the Script using Geonames.org's WebService
var script = document.createElement("script");
script.src = "http://ws.geonames.org/findNearbyPostalCodesJSON?lat=" + latitude + "&lng=" + longitude + "&callback=" + callback;
console.log(script.src);
// Run the Script
document.getElementsByTagName("head")[0].appendChild(script);
}
function callback(json)
{
zip = json.postalCodes[0].postalCode;
country = json.postalCodes[0].countryCode;
state = json.postalCodes[0].adminName1;
county = json.postalCodes[0].adminName2;
place = json.postalCodes[0].placeName;
alert(zip);
}
$('#findLocation').click(function(event) {
event.preventDefault();
console.log(zip); // This is giving me undefined currently
});
So basically, in the callback function, I want to store the zip code as a variable(rather than displaying it in an alert) and then in the on click function at the bottom, I want to be able to display the zip code that was stored in the previous callback function.
Any help greatly appreciated, still pretty new to Javscript/jQuery, thanks!
You could set zip as a 'global' variable by including it outside of the function at the top of the document like so:
var zip;
...
Alternatively, you may consider defining an object at the 'global' level and using it as a namespace to store variables like so:
window.address = {};
function callback(json){
address.zip = json.postalCodes[0].postalCode;
address.country = json.postalCodes[0].countryCode;
address.state = json.postalCodes[0].adminName1;
address.county = json.postalCodes[0].adminName2;
address.place = json.postalCodes[0].placeName;
}
$('#findLocation').click(function(event) {
event.preventDefault();
console.log(address.address);
console.log(address.zip);
...
});
I hope this helps!
Define var zip at very begining of code. You haven't defined it.
I haven't tried, but it should solve your problem.
Also, it seems that you forgot to define other variables in callback function as well.
What I would do, is to avoid the anonymous function in the event handler, that is, create a new named function -which gives you the added benefit of traceability during debugging- and then use that function as the event handler callback:
function eventHandlerFunction(event) {
var zip;
event.preventDefault();
zip = eventHandlerFunction.zip;
console.log(zip);
}
function callback(json) {
var zip;
zip = doSomethingWithJsonToGetTheZip();
eventHandlerFunction.zip = zip;
}
$("#findLocation").click(eventHandlerFunction);
Or, better yet, code this as a module and then you have member encapsulation and you can share variables amongst functions without modifying the global object. You never know when another library will modify the same global member that you are using.
var yourModule = (function($) {
var zip;
function retrieveZip(callback) {
// your code
}
function callback(json) {
// do something with json
zip = json.zip; // or whatever
}
$("#findLocation").click(function(event) {
event.preventDefault();
console.log(zip); // zip is visible in the parent scope + this scope
});
}(jQuery));

return a variable from .click() javascript function

First of all excuse for my weak english, I try to use the following javascript code and I want to return id variable and use it in other function, but it seem does not work correctly and does not return it, can someone help me out writting this
var idcb = $('.box').click(function() {
var id = $(this).attr('id');
return id;
});
I want to use var idcb in this function :
$(".hs").click(function() {
$(idhs).slideToggle("slow");
return false;
});
});
for that to work, the jquery click implementation would need to know that the function you pass it returns a value, and that it itself should return that value - which isn't the case.
instead, you could use some closure magic to do this easily. try this:
var idcb;
$('.box').click(function() {
idcb = $(this).attr('id');
});
You are passing an anonymous function to an event handler, you cannot return a value from this type of function. The solution is to use closures to get around this :
var idcb = null;
$('.box').click(function() {
idcb = $(this).attr('id');
});
The variable idcb will always be set to the id of the last .box that was clicked.
The function is given as a parameter to the click function and is run asynchronously when the user clicks on an element. So you can't return a value directly, since the function won't be run immediately. You can look up the id value another way, or pass it to a function to work with instead of returning it, or just do this:
var idcb = $('.box').click(function() {
var id = $(this).attr('id');
$(id).slideToggle("slow");
});
You cannot do it the way you are trying to. However, what you can do is use a variable that is accessible by both functions to share values between them.
var icdb = 'test';
function a() {
icdb = 'another value';
}
function b() {
console.log(icdb);
}
a();
b();
You could also call b from a and pass the variable as argument:
function a() {
b('test');
}
function b(icdb) {
console.log(icdb);
}
a();
your variable idcb contains the click handler !
you need to declare the vriable outside the handler and assign to it inside to make this work:
var idcb = null;
// ... whatever
$('.box').click(function() {
idcb = $(this).attr('id');
return true; // return 'true' from an event handler to indicate successful completion
});
Check this out
var id=null;
$('.box').click(function() {
id = $(this).attr("id");
});
$(".hs").click(function() {
$("#"+id).slideToggle("slow");
return false;
});
You could pass in the an object as a reference to the click function
and change the value from the callback. Another option is using closures
The caveat to this jsfiddle is that you have to call a .box element first.
http://jsfiddle.net/D6B73/2/
var idcb = {};
$('.box').click(idcb, function (event) {
event.data.value = $(this).attr('id');
console.log(idcb.value);
});
$('.hs').click(function() {
$('#'+idbc.value).slideToggle("slow");
});
You can do it this way:
$(".hs").on('click', function() {
var id = $('.box').attr('id');
alert(id);
});

Categories

Resources