Reputation: 2967
I have this script:
var d;
$(".circle").click(function() {
var id = $(this).attr('id');
var MyDiv1 = document.getElementById(id);
var name = MyDiv1.innerHTML;
$.get("url", function(data){
d=data;
});
d=d.split(",");
var arrayLength = d.length;
for (var i = 0; i < arrayLength; i++) {
if(i==id)
custom_alert(d[i], name);
}
});
I want to call
d = d.split(",");
Only after I'm sure d isn't undefined
.
How do I execute that after the $.get
functions finishes and d is assigned to the data?
Upvotes: 0
Views: 87
Reputation: 138237
You could simply put it into the callback? :
$.get("url", function(d){
d=d.split(",");
var arrayLength = d.length;
for (var i = 0; i < arrayLength; i++) {
if(i==id)
custom_alert(d[i], name);
}
});
Or using ES7 (very new stuff) :
(async function(){
var d=await new Promise(function(r){
$.get("url",r);
});
d=d.split(",");
...
})();
Upvotes: 3
Reputation: 1892
jQuery.get() is asynchronous because it is a shorthand for jQuery.ajax() who's default option for requests is async: true.
Read here about asynchronous requests.
// declare it here if you need its values later (to be a global variable), or move it inside function(){ } declared inside $.get() call.
var d;
$(".circle").click(function() {
var id = $(this).attr('id');
var MyDiv1 = document.getElementById(id);
var name = MyDiv1.innerHTML;
$.get("url", function(data){
d=data;
// $.get has an asynchronous answer (you don't know when it will come or if it comes). Call d.split here
d=d.split(",");
var arrayLength = d.length;
for (var i = 0; i < arrayLength; i++) {
if(i==id)
custom_alert(d[i], name);
}
});
});
Upvotes: 2
Reputation: 5425
You can only rely on d
to have a value in the block where it is assigned a value, which is inside the callback function(data){...}
.
var d;
$(".circle").click(function() {
var id = $(this).attr('id');
var MyDiv1 = document.getElementById(id);
var name = MyDiv1.innerHTML;
$.get("url", function(data){
d=data.split(",");
var arrayLength = d.length;
for (var i = 0; i < arrayLength; i++) {
if (i==id)
custom_alert(d[i], name);
}
});
});
Upvotes: 1
Reputation: 353
You need to put the JS that depends on d being defined inside the get callback.
var d;
$(".circle").click(function() {
var id = $(this).attr('id');
var MyDiv1 = document.getElementById(id);
var name = MyDiv1.innerHTML;
$.get("url", function(data){
d=data;
d=d.split(",");
var arrayLength = d.length;
for (var i = 0; i < arrayLength; i++) {
if(i==id)
custom_alert(d[i], name);
}
});
});
Upvotes: 2