0

I have defined a JavaScript function

function a()

 {
    var data = 'some data';
    $.getJSON(networkController,data,function(r) {
            $.each(r, function(a)
            {
                alert(r[a].networkAccessToken);
        });
   });
}

It works fine but When I do it as:

 function a()

 {
    var data = 'some data';
    $.getJSON(networkController,data,function(r) {
            $.each(r, function(a)
            {
                return r[a].networkAccessToken;
        });
  });
 }
var c = a();
alert(c);

Alert is undefined.....

7
  • 1
    check again .....It is right syntax other wise give total code Commented Apr 24, 2012 at 6:02
  • How are you fetching the value from the database? Are you sure the value is parsed correctly? Commented Apr 24, 2012 at 6:02
  • 1
    can we see the code that sets the value for b or what is it.. Commented Apr 24, 2012 at 6:05
  • if function a() is callback function of ajax call then if you call it directly it will not have value b unless called asynchronously by ajax engine. Commented Apr 24, 2012 at 6:06
  • 1
    @RanaMuhammadUsman, pls add the above code to the question. Commented Apr 24, 2012 at 6:09

2 Answers 2

3

It's important to realise that your AJAX call is non-blocking. This means that it returns before a response is received from the server. (The first "A" stands for "Asynchronous"!)

The most common way to handle this is to use a callback:

 function a(callback) {
    var data = 'some data';
    $.getJSON(networkController,data,function(r) {
        $.each(r, function(a) {
            callback(r[a].networkAccessToken);
        });
    });
 }

 a(function(c) {
   alert(c);
 });
Sign up to request clarification or add additional context in comments.

Comments

0

You have two problems.

First, Asynchronous JavaScript and XML is Asynchronous. When you call $.getJSON it sends an HTTP request and registers a function to run when the data gets back. It then gets one with running the existing function while it waits for that.

You are effectively trying to do something like:

function a() {
    $('button').click(function () { return 1; });
}
foo = a(); // Would you expect this to be `1` and not `undefined`?

Second, each calls a function for each value. The function you pass to each is called by each not getJSON or a. Its return value only determines if the loop should be continued or not.

You need to do whatever you want to do in the function you pass to each. You can't pass data back up the calling chain. What you want to pass back to no longer exists.

1 Comment

Is that not ok return $.each(r, function(){ return r[a].networkAccessToken; });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.