I want to execute this function and use the variable outside the function, but inside an each function. How can I get this to work?
$('.social').each(function() {
url = "http:www.google.com";
bit_url(url);
$(element).append(urlshortened);
});
function bit_url(url) {
var url = url;
var username = "...";
// bit.ly username
var key = "...";
$.ajax({
url : "http://api.bit.ly/v3/shorten",
data : {
longUrl : url,
apiKey : key,
login : username
},
dataType : "jsonp",
success : function(v) {
urlshortened = v.data.url;
}
});
}
The “A” in Ajax stands for Asynchronous code won’t work like that, you need callbacks.
Deferred.doneis an equivalent to$.ajax‘ssuccess, I’ve attached thedonehandler inside the.eachscope so your callback can access all variables from the.eachscope.Though, if
$(element)is always the same element, you will be fine with @JohnJohnGa’s answer by putting theappendinside the success handler.I assume you want to replace anchors’
hrefinside the.eachdue to the question nature, so you’d store a reference to the link inside of the.eachand use that reference inside the callback.