exctracting a variable from a jquery method [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I want to extract the variable response from the mentionsInput() method and using it outside this method, but when I try an alert() on this variable it's empty.
jQuery(document).ready(function() {
var choix = $('#choixaide').val();
var choix_sous_theme1 = $('#choix_sous_theme1aide').val();
$('textarea.mention1').mentionsInput('val', function(text) {
var response = text;
});
alert(response);
});
Thanks for your help.

As you have it now, response is only available within the scope of your mentionsInput method, but not outside of it.
Additionally, when running your code, I see the following error:
Uncaught TypeError: $(...).mentionsInput is not a function"...
Are you sure you've properly loaded the jquery.mentionsInput UI component? You'll need to solve for this error first, if you are also encountering this.
Then, you'll need to declare the variable response prior to and outside of your mentionsInput method, and then set it within mentionsInput. The value set for response should then be available in the same scope as your alert call.

I think this should do the trick:
jQuery(document).ready(function() {
var choix = $('#choixaide').val();
var choix_sous_theme1 = $('#choix_sous_theme1aide').val();
var response = $('textarea.mention1').val();
alert(response);
});

Related

Javascript Variable not updating/saving [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How can I save information locally in my chrome extension?
(2 answers)
Closed 5 years ago.
I have a string which I need in multiple functions. Therefore I want to save it in a variable. But when I try to assign it inside a function it doesn't update the variable.
var auth_code = "na";
function safeAuthCode(authcode){
auth_code = authcode;
console.log(auth_code);
}
"auth_code" prints just fine in the console at that point, but when I try to use it later it just contains "na". Not sure what I'm doing wrong tbh :/
Edit:
This is the function in which safeAuthCode is called:
function auth(){
chrome.identity.launchWebAuthFlow({
"url": "https://accounts.spotify.com/authorize?client_id="+client_id+
"&redirect_uri="+ encodeURIComponent(redirectUri) +
"&response_type=code"+
"&scope=" + encodeURIComponent(scopes),
"interactive": true
},
function(redirect_url) {
var url = new URL(redirect_url);
var code = url.searchParams.get("code");
safeAuthCode(code);
});
}
I am assuming that the problem you are having is because of the global variable that either gets overwritten in a different part of the code, or because your code at a certain point in time reloads, and the initial value gets reset.
To save such authentication code, you could make use of the sessionStorage object of your browser.
To make sure you only have 1 such object, you could use the const keyword to define your variables (in case another definition of that variable would come at a later time, you should get an error thrown)
const authorisationSettings = {
get code() {
return sessionStorage.getItem('authorisationCode') || 'na';
},
set code(value) {
return sessionStorage.setItem('authorisationCode');
}
};
function saveAuthorisationCode( code ) {
authorisationSettings.code = code;
}
saveAuthorisationCode( 'test' );
console.log( authorisationSettings.code );
This snippet doesn't work on stackoverflow, so you can find the jsfiddle here
It happens because of when your function is executed, in lexical environment of that function is already exist authcode variable and you are trying to set this one instead of global authcode
You need to change name of global variable or param of the fuction...

Unexpected Uncaught TypeError [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
This code is an external file, test.js, which is linked to from index.html, after the jQuery file.
When I refresh my browser and go into the console, I get this error message:
Uncaught TypeError: Cannot read property 'starshipName' of undefined
on line 20, where I try to alert the starshipName property of the first item in the array.
var starships = [];
function starship(starshipName, model, manufacturer) {
this.starshipName = starshipName;
this.model = model;
this.manufacturer = manufacturer;
}
function starshipData(data) {
for (i = 0; i < data.results.length; i++) {
var results = data.results[i];
starships.push(new starship(results["name"], results["model"], results["manufacturer"]));
}
}
$.getJSON('https://swapi.co/api/starships/', function(data) {
starshipData(data);
});
alert(starships[0].starshipName);
However, when I type out the last line of code or log the starships array to the console, it works perfectly. I am very confused as to why this is happening and will appreciate any help! Thank you in advance.
$.getJSON is an asynchronous function. This means that your alert() is called before starships is filled with data - hence the undefined property error.
All operations that depend on an async function must be placed in, or called from, the callback. Try this:
$.getJSON('https://swapi.co/api/starships/', function(data) {
starshipData(data);
// 1: place the call in the callback
// 2: always use console.log to debug as it does not coerce data types
console.log(starships[0].starshipName);
});

PhantomJS: call a user defined/custom function within phantomjs [duplicate]

This question already has an answer here:
Cannot pass module functions to Page
(1 answer)
Closed 6 years ago.
i'm getting a ReferenceError when i call a function i defined myself inside the page.evaluate() of Phantom; what is the proper way to do that ?
for example:
function mySweetFunction(item) {
// process item....
}
page.evaluate(function(){
var item= document.getElementsById('item');
mySweetFunction(item);
});
then i'll get the error:
ReferenceError: Can't find variable: mySweetFunction
What is the proper way to do this ?
mySweetFunction is quite big, and i would prefer to keep it out of page.evaluate(...) if possible.
If you want to use a function inside page.evaluate() you have to put it there first:
page.evaluate(function(){
function mySweetFunction(item) {
// process item....
}
var item = document.getElementsById('item');
mySweetFunction(item);
});

Can't use variable from anonymous function outside scope in javascript [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I have a very simple setup:
var genres;
$.get('/api/genres', '', function (response) {
genres = response.data
}, 'json');
$("#genre").tagit({
availableTags: genres //this doesn't work
});
For some reason the genres variable is not accessible inside the tagit method. How would I achieve this?
$.get is asynchronous. It's not that genres is not accessible inside .tagit. Your problem is that by the time you try to use it, it's still unassigned. A way to fix it would be moving your .tagit function inside the callback:
var genres;
$.get('/api/genres', '', function (response) {
genres = response.data
$("#genre").tagit({
availableTags: genres //this doesn't work
});
}, 'json');
I also recommend reading $.get's documentation.

variables in $.get() function: can't access out of that function again? [duplicate]

This question already has answers here:
Get var out of jQuery.get nested function
(2 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have another javascript/jQuery's variables scope questions to ask...
Say I declared a object named Container. In which there is a variables called myimage which will read a address from some xml file.
Container = function()
{
var myimage;
}
Container.prototype.readXML = function()
{
$.get("assest/xml/images.xml",function(xml)
{
//Read in URL path from XML file, and store them into memeber variables
myimage = $(xml).find('background').text();
//Apply background image into body, and apply css styple into it
$("body").css('background-image','url(' + myimage + ')');
//This alert will work
alert(myimage);
});
//This alert gives not defined variable
alert(myimage);
}
Please look at the two alert section. It seems this variable I defined in the Container object, can only work inside that readXML function. but not out. I can't understand why this happend.
I do use some other notation, like declare with
this.myimage
and access it by change name of this to self before execute the $.get function
var self= this;
But it get worse. Sometimes it even can't be reached anymore inside the get function.
Could you help me with this? My final goal is an array in that object and read bunch of data from XML than display them into HTML. If the variables I set in the Object can't be reached, there is no way I can do that.
Thank you!!
Container = function()
{
var myimage;
}
should most likely be defined as below. More importantly, $.get is asynchronous so you cannot assume it finishes each line of code in the order it's written.
var Container = function()
{
this.myimage = '';
}
Container.prototype.readXML = function(callback) {
$.get("assest/xml/images.xml", function(xml) {
//Read in URL path from XML file, and store them into memeber variables
this.myimage = $(xml).find('background').text();
//Apply background image into body, and apply css styple into it
$("body").css('background-image', 'url(' + this.myimage + ')');
//This alert will work
callback(this.myimage);
});
}​
var instance = new Container();
instance.readXML(function (copy) {
alert(copy);
});​
All variables in Javascript that are not declared in the global scope are local to the function they are declared in.
Since functions are objects in Javascript, you can assign properties to them. So, you can do
Container.myimage = $(xml).find('background').text();
//...
alert(Container.myimage);

Categories

Resources