Rectangle 27 4

It has to do with variable scope. The local variable pinNumber you create is not accessible outside its wrapping function.

Perhaps declare pinNumber globally or if it'll do the trick, simply stick your .append() inside your success function.

It has nothing to do with variable scope; the .append is executing before the success callback.

async is false though, meaning .append will run after the AJAX call.

OP doesn't need to declare the pinNumber globally, it will suffice to not use the var keyword in the assignment to it inside the success handler. The assignment will then affect the enclosing scope.

javascript - jQuery ajax return value - Stack Overflow

javascript jquery variables
Rectangle 27 3

It has to do with variable scope. The local variable pinNumber you create is not accessible outside its wrapping function.

Perhaps declare pinNumber globally or if it'll do the trick, simply stick your .append() inside your success function.

It has nothing to do with variable scope; the .append is executing before the success callback.

async is false though, meaning .append will run after the AJAX call.

OP doesn't need to declare the pinNumber globally, it will suffice to not use the var keyword in the assignment to it inside the success handler. The assignment will then affect the enclosing scope.

javascript - jQuery ajax return value - Stack Overflow

javascript jquery variables
Rectangle 27 3

It has to do with variable scope. The local variable pinNumber you create is not accessible outside its wrapping function.

Perhaps declare pinNumber globally or if it'll do the trick, simply stick your .append() inside your success function.

It has nothing to do with variable scope; the .append is executing before the success callback.

async is false though, meaning .append will run after the AJAX call.

OP doesn't need to declare the pinNumber globally, it will suffice to not use the var keyword in the assignment to it inside the success handler. The assignment will then affect the enclosing scope.

javascript - jQuery ajax return value - Stack Overflow

javascript jquery variables
Rectangle 27 3

It has to do with variable scope. The local variable pinNumber you create is not accessible outside its wrapping function.

Perhaps declare pinNumber globally or if it'll do the trick, simply stick your .append() inside your success function.

It has nothing to do with variable scope; the .append is executing before the success callback.

async is false though, meaning .append will run after the AJAX call.

OP doesn't need to declare the pinNumber globally, it will suffice to not use the var keyword in the assignment to it inside the success handler. The assignment will then affect the enclosing scope.

javascript - jQuery ajax return value - Stack Overflow

javascript jquery variables
Rectangle 27 7

The reason the second example works is because you're defining myvar as a global variable (which is accessible from anywhere).

The first example doesn't work because the variable is defined within functional scope (meaning it's inaccessible from all except that function's scope, and the scope of functions defined within that parent function's scope).

As stated in the comments, this is just how JavaScript works. If this is a problem you're running into then it's probably time to rethink your architecture.

One common pattern is to define shared variables as properties of parent objects or functions. For example:

$(function() {
    var funcOne = function() {
        this.sharedVal = 'stack overflow';
    };
    var funcTwo = function() {
        console.log(funcOne.sharedVal);
    };
});

This way you can have distinct functions that are able to share their properties from within other within other functions, whilst also keeping the global namespace clean. Note, however, that in this example, a simple var x = 'something'; which isn't bound as a property of another function would do just as well.

javascript - How to get variables from the outside, inside a function ...

javascript jquery
Rectangle 27 4

You can also use $rootScope for global access in AngularJS

app.controller('loginController', function ($scope,$rootScope,$location){

   $scope.loginUser = function (user) {

       $rootScope.userId = "USERID";
       $location.path('/view3');

   }
});

app.controller('videoListController', function($scope, $rootScope){

alert("UserID: "+$rootScope.userId);               

});

javascript - Scope variable not accessible (undefined) - AngularJS - S...

javascript angularjs angularjs-scope single-page-application undefined-reference
Rectangle 27 7

Just to add to the other answers, scope is a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code. This look-up may be for the purposes of assigning to the variable, which is an LHS (lefthand-side) reference, or it may be for the purposes of retrieving its value, which is an RHS (righthand-side) reference. These look-ups are what the JavaScript engine is doing internally when it's compiling and executing the code.

So from this perspective, I think that a picture would help that I found in the Scopes and Closures ebook by Kyle Simpson:

The building represents our programs nested scope ruleset. The first floor of the building represents your currently executing scope, wherever you are. The top level of the building is the global scope. You resolve LHS and RHS references by looking on your current floor, and if you dont find it, taking the elevator to the next floor, looking there, then the next, and so on. Once you get to the top floor (the global scope), you either find what youre looking for, or you dont. But you have to stop regardless.

One thing of note that is worth mentioning, "Scope look-up stops once it finds the first match".

This idea of "scope levels" explains why "this" can be changed with a newly created scope, if it's being looked up in a nested function. Here is a link that goes into all these details, Everything you wanted to know about javascript scope

What is the scope of variables in JavaScript? - Stack Overflow

javascript variables scope
Rectangle 27 6

Just to add to the other answers, scope is a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code. This look-up may be for the purposes of assigning to the variable, which is an LHS (lefthand-side) reference, or it may be for the purposes of retrieving its value, which is an RHS (righthand-side) reference. These look-ups are what the JavaScript engine is doing internally when it's compiling and executing the code.

So from this perspective, I think that a picture would help that I found in the Scopes and Closures ebook by Kyle Simpson:

The building represents our programs nested scope ruleset. The first floor of the building represents your currently executing scope, wherever you are. The top level of the building is the global scope. You resolve LHS and RHS references by looking on your current floor, and if you dont find it, taking the elevator to the next floor, looking there, then the next, and so on. Once you get to the top floor (the global scope), you either find what youre looking for, or you dont. But you have to stop regardless.

One thing of note that is worth mentioning, "Scope look-up stops once it finds the first match".

This idea of "scope levels" explains why "this" can be changed with a newly created scope, if it's being looked up in a nested function. Here is a link that goes into all these details, Everything you wanted to know about javascript scope

What is the scope of variables in JavaScript? - Stack Overflow

javascript variables scope
Rectangle 27 6

Just to add to the other answers, scope is a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code. This look-up may be for the purposes of assigning to the variable, which is an LHS (lefthand-side) reference, or it may be for the purposes of retrieving its value, which is an RHS (righthand-side) reference. These look-ups are what the JavaScript engine is doing internally when it's compiling and executing the code.

So from this perspective, I think that a picture would help that I found in the Scopes and Closures ebook by Kyle Simpson:

The building represents our programs nested scope ruleset. The first floor of the building represents your currently executing scope, wherever you are. The top level of the building is the global scope. You resolve LHS and RHS references by looking on your current floor, and if you dont find it, taking the elevator to the next floor, looking there, then the next, and so on. Once you get to the top floor (the global scope), you either find what youre looking for, or you dont. But you have to stop regardless.

One thing of note that is worth mentioning, "Scope look-up stops once it finds the first match".

This idea of "scope levels" explains why "this" can be changed with a newly created scope, if it's being looked up in a nested function. Here is a link that goes into all these details, Everything you wanted to know about javascript scope

What is the scope of variables in JavaScript? - Stack Overflow

javascript variables scope
Rectangle 27 6

Just to add to the other answers, scope is a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code. This look-up may be for the purposes of assigning to the variable, which is an LHS (lefthand-side) reference, or it may be for the purposes of retrieving its value, which is an RHS (righthand-side) reference. These look-ups are what the JavaScript engine is doing internally when it's compiling and executing the code.

So from this perspective, I think that a picture would help that I found in the Scopes and Closures ebook by Kyle Simpson:

The building represents our programs nested scope ruleset. The first floor of the building represents your currently executing scope, wherever you are. The top level of the building is the global scope. You resolve LHS and RHS references by looking on your current floor, and if you dont find it, taking the elevator to the next floor, looking there, then the next, and so on. Once you get to the top floor (the global scope), you either find what youre looking for, or you dont. But you have to stop regardless.

One thing of note that is worth mentioning, "Scope look-up stops once it finds the first match".

This idea of "scope levels" explains why "this" can be changed with a newly created scope, if it's being looked up in a nested function. Here is a link that goes into all these details, Everything you wanted to know about javascript scope

What is the scope of variables in JavaScript? - Stack Overflow

javascript variables scope
Rectangle 27 4

It's a general issue in JavaScript. I found this answer very helpful.

When you run console.log(this), you output the object itself and the console links references (pointers if you like) to the inner variables.

Thanks, so this looks like I would have to write my own loging function which loops trough an object and console.log() all its content manually. Otherwise I will always see the "final state" in the console.

Are you setting 'output' in an asynchronous operation? I had the same problem some time ago with Backbone but I don't remember the exact solution.

Yes I am, I for now solved it with a combination of an angular promise and a setInterval which checks if the value is set. But the problem is, that when there is no value for "output" in the database it is as well undefined as when it's still loading. So I had to add a max waiting time which I hate to. But that's another topic. I'm going to accept your answer because it helped me to understand how objects are handled within console.log which was the most confusing part for me. Thanks!

if output is async it might work to deep watch, setting a true parameter such as: $scope.$watch('output', function(newdata, olddata){/*...*/}, true);

javascript - Property defined in scope object but not accessible - Sta...

javascript angularjs angularjs-directive console.log
Rectangle 27 32

$.getJSON is asynchronous. That is, the code after the call is executed while $.getJSON fetches and parses the data and calls your callback.

The order of the calls of a, b, and c may be either a b c (what you want, in this case) or a c b (more likely to actually happen).

Make the request synchronous instead of asynchronous:

a();

$.ajax({
    async: false,
    url: "url",
    success: function() {
        b();
    }
});

c();

Move the call to c after the call to b:

a();

$.getJSON("url", function() {
    b();

    c();
});

Thanks strager for the quick reply. You'll have to forgive me.. even with a CS degree, I'm still kind of a noob at some of this stuff. I think I've seen that you can set async to false in the $.ajax(..)? Can I just say "$.ajax({async: false});"? Also, and maybe more importantly, what will it means once asynchronous is turned off? Everything executes top to bottom? Thanks again..

A sound answer. Unfortunately (as the OP has discovered in the question update), $.getJSON does not provide an "option override" for the asynch option. @Mega Matt: you'll have to call $.ajax instead of $.getJSON, passing dataType:"json" in order to perform the same work of getJSON.

There's no good reason to be synchronous rather than async. Just put the code into the callback.

Woops, I meant async, not asynch. Another option that comes to mind is to set a "global" override via $.ajaxSettings.async = false. Note that this affects all XMLHttpRequests.

I didn't mean always, @strager, I meant in JavaScript Ajax programs. $document ready is meant for setting up things like click handlers. Doing stuff sync instead of async in JavaScript is a bad idea because JS is single threaded and the thread can't end. The interface gums up and some browsers will throw up alerts about the script not ending. Since the goal of learning Ajax is usually to create responsive web pages or RIAs (not command line apps), async is what's needed to be learned.

javascript - Variables set during $.getJSON function only accessible w...

javascript jquery variables scope callback
Rectangle 27 1

Scope is defined per controller... You still have the option to use $scope.$parent or $rootScope to link controllers but I would use those carefully.

Angular Services are based on singleton patterns. You can also use those to share information between controllers and I think it will be the best approach.

I found that this has been previously discussed and here are some good examples:

javascript - Scope variable not accessible (undefined) - AngularJS - S...

javascript angularjs angularjs-scope single-page-application undefined-reference
Rectangle 27 2

$scope isn't shared between controllers. If you need to pass data between controllers, it needs to be stored somewhere else that is persistent.

Oh ok. What would you say is the best way to pass variables between controllers then?

javascript - Scope variable not accessible (undefined) - AngularJS - S...

javascript angularjs angularjs-scope single-page-application undefined-reference
Rectangle 27 1

JavaScript has function scope. That means that variables (including function declarations) defined within a function, will only be available in that function. i.e. in this case back_to_top is only accessible within the $(function(){...}).

...onClick="back_to_top();" is looking at the global scope and back_to_top is not available. You can expose it though if you do something like this:

$(function () {
        window.back_to_top = function {
            $('body,html').animate({scrollTop: 0}, 100);
        }
    });

I don't think this is ideal but it will work in your case. A better way is to attach a listener. Have a look at jQuery click method.

javascript - jquery: Uncaught ReferenceError: function is not defined ...

javascript jquery
Rectangle 27 4

Create a global variable

window.Example = Example

coffeescript Class not accessible in main javascript - Stack Overflow

javascript coffeescript
Rectangle 27 7

Remember that when you supply a callback function, the point of that is to defer the execution of that callback until later and immediately continue execution of whatever is next. This is necessary because of the single-threaded execution model of JavaScript in the browser. Forcing synchronous execution is possible, but it hangs the browser for the entire duration of the operation. In the case of something like $.getJSON, that is a prohibitively long time for the browser to stop responding.

var foo = {};

$.getJSON("url", function(data) {
  foo = data.property;
});

// Use foo here.
$.getJSON("url", function(data) {
  // Do something with data.property here.
});

"Do something" could be a call to another function if you want to keep the callback function simple. The important part is that you're waiting until $.getJSON finishes before executing the code.

You could even use custom events so that the code you had placed after $.getJSON subscribes to an IssuesReceived event and you raise that event in the $.getJSON callback:

Or, you could store the data globally and just use the custom event for notification that the data had been received and the global variable updated.

$(document).ready(function() {
  $(document).bind('IssuesReceived', IssuesReceived)

  $.getJSON("url", function(data) {
    // I prefer the window.data syntax so that it's obvious
    //  that the variable is global.
    window.data = data;

    $(document).trigger('IssuesReceived');
  });
});

function IssuesReceived(evt) {
  // Do something with window.data here.
  //  (e.g. create the drag 'n drop interface)
}

// Wired up as the "drop" callback handler on 
//  your drag 'n drop UI.
function OnDrop(evt) {
  // Modify window.data accordingly.
}

// Maybe wired up as the click handler for a
//  "Save changes" button.
function SaveChanges() {
  $.post("SaveUrl", window.data);
}

Does anyone have an idea how I should be blocking user interaction while this is going on? Why is it such a concern? Thanks again for all the responses.

The reason that you should avoid blocking the browser with synchronous AJAX calls is that a blocked JavaScript thread blocks everything else in the browser too, including other tabs and even other windows. That means no scrolling, no navigation, no nothing. For all intents and purposes, it appears as though the browser has crashed. As you can imagine, a page that behaves this way is a significant nuisance to its users.

Thanks for the answer Dave. So I want run a scenario by you. Let's say, within the $.getJSON callback, I take the data that I get from the call, and load a jquery drag drop list that the user can then remove Issues from if he chooses. The user doesn't want a particular Issue assigned to him, and "drops" it. Then he wants to save that list that is assigned to him. Here I want to update that information, and a JSON object would be perfect. But I no longer have access to that info because the callback has finished executing. I don't have a list to remove an Issue from! How should I handle this?

@Nosredna: Custom events are very underused, IMO. They're great for cleaning up the nested anonymous function spaghetti that inline event handlers tend to produce.

Dave, I think your answer may violate my original issue with asynchronous calling. A global variable seems like a good solution, but only if I can ensure that it is called after the $.getJSON runs. If I need to be able to manipulate the data after the callback completes, it sounds like the only I can store that data is in a variable outside of the scope of the callback (and within the scope I need it). And the only way to ensure that the variable's values are set it to set ajax to sync. Good conclusion?

@Matt: Take a look at my recent edits, including the OnDrop and SaveChanges functions, and see if that makes sense. With event-driven code, the idea is to act on these events as necessary, not to orchestrate a certain chain of code to execute all in synchronous order. Anything else is going against the grain when you're working in the single-threaded browser environment; especially when using an event-driven framework like jQuery.

javascript - Variables set during $.getJSON function only accessible w...

javascript jquery variables scope callback
Rectangle 27 5

$variable= new array();

$.getJSON("url", function(data){
asignVariable(data);
}

function asignVariable(data){
$variable = data;
}

console.log($variable);

javascript - Variables set during $.getJSON function only accessible w...

javascript jquery variables scope callback
Rectangle 27 46

JavaScript doesn't have block scope, just function scope. Since the initialization of i is within one function, that variable is accessible anywhere else in that same function.

Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.

this is great reproducibility but disrupts what sun's java was trying to establish.

JavaScript loop variable scope - Stack Overflow

javascript variables for-loop scope
Rectangle 27 1

Self invoked function in javascript:

A self-invoking expression is invoked (started) automatically, without being called. A self-invoking expression is invoked right after its created. This is basically used for avoiding naming conflict as well as for achieving encapsulation. The variables or declared objects are not accessible outside this function. For avoiding the problems of minimization(filename.min) always use self executed function.

closures - What is the purpose of a self executing function in javascr...

javascript closures iife self-executing-function