parse
looks like a global variable so it will be available anywhere. The issue is probably when you're trying to access it. You can ONLY access parse
in your .done()
handler or some function you call from that.
The reason for this is that your ajax call is asynchronous. That means that the operation starts, the rest of your javascript continues to execute and then SOMETIME LATER the ajax call completes and ONLY then is the parse
variable valid. Because of this, there really is no reason to declare the parse
variable the way you have. You should just use its value inside the .done()
handler.
This is asynchronous programming and works differently than synchronous, sequential programming. You must use asynchronous programming techniques with asynchronous ajax calls.
If you try to access parse
inside the .done()
handler and it's still empty in there, then the issue is likely that data.item
isn't what you think it is and maybe isn't triggering the .each()
loop and thus nothing is getting put into foo
or parse
. To debug this case, you should look at what exactly is in data
and data.item
.
This would be my suggestion:
$.ajax({
type: "GET",
url: "some/path/",
data: somedata
}).done(function( data ){
// no reason for these variables to be wider scope than here
var foo = [], parse;
$.each(data.item, function(i, value){
foo.push(value);
});
parse = foo.join(', ');
// look at parse here
console.log(parse);
// if parse still empty, then look at data and data.item here
// to see what they are for debug reasons
console.log(data);
console.log(data.item);
// now, you can use parse here
callSomeFunction(parse);
});