[jQuery] Re: Frustrating Scope Question with getJSON

2009-09-19 Thread Michael Geary
In other words, you have to redesign your shortenURL function, like this:

function shortenURL( url, callback ) {
var apiKey = 'APIKEY';
var apiLogin = 'LOGIN';
$.getJSON(
"http://api.bit.ly/shorten?version=2.0.1&longUrl=";
+ url + "&login=" + apiLogin + "&apiKey=" + apiKey,
function( data ) {
callback( data.results[url].shortUrl );
}
);
}

and call it like this:

shortenURL( 'http://www.example.com/', function( url ) {
alert( 'Short URL is: ' + url );
});

-Mike

On Sat, Sep 19, 2009 at 10:00 AM, MorningZ  wrote:

>
> On Sep 19, 11:34 am, Bill H  wrote:
> > I've tried that and still can't seem to get the data into any sort of
> > usable scope.
>
> The problem is that while you may be understanding scope, you are not
> understanding asynchronous calls the $.getJSON call doesn't
> "return" anything
>
> Whatever you are wanting to do with "shortURL" needs to be done
> inside, or at least kicked off from inside, the getJSON's success event
>


[jQuery] Re: Frustrating Scope Question with getJSON

2009-09-19 Thread MorningZ

On Sep 19, 11:34 am, Bill H  wrote:
> I've tried that and still can't seem to get the data into any sort of
> usable scope.

The problem is that while you may be understanding scope, you are not
understanding asynchronous calls the $.getJSON call doesn't
"return" anything

Whatever you are wanting to do with "shortURL" needs to be done
inside, or at least kicked off from inside, the getJSON's success event


[jQuery] Re: Frustrating Scope Question with getJSON

2009-09-19 Thread Bill H

I've tried that and still can't seem to get the data into any sort of
usable scope.


[jQuery] Re: Frustrating Scope Question with getJSON

2009-09-19 Thread Dave Methvin

> I'd ideally just like the function to return the shortUrl from the
> json results but can't seem to get it anywhere but the callback
> function.

...

>          $.getJSON("http://api.bit.ly/shorten?version=2.0.1&longUrl=";
> + url + "&login=" + apiLogin + "&apiKey=" + apiKey, function(data){
>                                 shortURL = data.results[url].shortUrl;
>                     });
>          return shortURL;

You're returning shortURL from the function before $.getJSON has
returned! The shortenURL function can't run synchronously and return
the URL if it's calling an asynchronous ajax method. Instead of
returning the URL, the function should pass in a callback.