0

Possible Duplicate:
How to return a value from a function that calls $.getJSON?

This seems very basic, but I can't figure out what is happening. I am using Firebug, but I'm not getting any errors when I run the script.

Here is my JS function:

function getMainContactCount()
{
    $.getJSON('<?php echo site_url('get_leads/main_contact'); ?>', 
         function(data) {
             return data.length;
                }
        );
}

If I set a variable equal to this function like var x = getMainContactCount(), I get nothing. Yet, I can console.log the value of data.length and it returns the correct value. What am I doing wrong? I also tried setting a variable equal to data.length in the anonymous function and then returning it below the JSON call, but that didn't work either.

Community
  • 1
  • 1
sehummel
  • 5,476
  • 24
  • 90
  • 137
  • 2
    Please search stackoverflow. There was a duplicate of a duplicate of a duplicate of this very same thing not 10 minutes ago :( –  Mar 13 '12 at 23:59
  • For what? This seems very general. – sehummel Mar 13 '12 at 23:59
  • For "jquery json return value" and yes, it is very general. It has to do with *asynchronous* events. –  Mar 14 '12 at 00:00
  • possible duplicate of [How to return a value from a function that calls $.getJSON?](http://stackoverflow.com/questions/4200641/how-to-return-a-value-from-a-function-that-calls-getjson) , http://stackoverflow.com/questions/6834194/get-returned-value-from-function-called-by-getjson –  Mar 14 '12 at 00:02
  • (Even if `getJSON` *did* return the JSON, it still wouldn't work because there is no `return` in `getMainContactCount` so it always evaluates to `undefined` when invoked. –  Mar 14 '12 at 00:05

0 Answers0