sehummel
sehummel

Reputation: 5568

Jquery: How to assign a JSON value to a function call

Before you go saying this is a duplicate or even closing it, please read the entire post. I've searched on here and what I am trying to do is different than what is posted on this site. The difference is, I am trying to assign a value from a JSON call to a function (one of several similar functions) so I can add the numbers returned for a total.

So if I have a JSON call like this:

var count;
function getMainContactCount {
    $.getJSON(url, function(data) {
       count = data;
       c= getCount(count);
       return c;
    });
}

function getCount(count) {
    return count;
}

Please note that my second function says return count not alert count. This works fine with alert because alert happens immediately and apparently return does not.

Then in my document ready (the above scripts are in an attached script file), I do this:

c= getMainContactCount();
count = getCount(c);

This clearly isn't going to work, but this is the essence of what I need to do. I need in my document ready to be able to return all of the counts from the database and then add them together. There are about 10 tables, so it seemed easier to return all the values into the document ready and then add them. But this may not be the right approach. What I don't want to do is alert the values, since that doesn't help me add the values.

Upvotes: 0

Views: 145

Answers (2)

bfavaretto
bfavaretto

Reputation: 71908

I think you are looking for something like this:

var count;
function getMainContactCount {
    $.getJSON(url, function(data) {
       count += data.length;
       // Whatever you you need to do with count, do it here.
       // Like this:
       alert(count) // just checking if we have the right value
                    // couldn't resist adding an alert :)
    });
}

EDIT

To reuse the same callback, define it outside the getJSON call:

 // Define a global count var
 var count;
 // Define a single callback to reuse
 var addCount = function(data) {
     count += data.length;
     alert(count); // just a test, remove the alert later
 }
 // Do several ajax calls to the json
 $.getJSON('/some_url', addCount);
 $.getJSON('/some_other_url', addCount);
 $.getJSON('/yet_another_url', addCount);

Upvotes: 1

Andrew
Andrew

Reputation: 13853

First off, getJSON is asynchronous. So getMainContactCount actually does not return anything.

Secondly, count = getCount(c) is equivalent to count = c.

What are you trying to do here?

If you want to get a value then use it later, split up your script execution, on load

var myPageLoadingScripts = function(count){  
  //You can use count here.  
  ...
}

$(function(){
    $.getJSON(url, myPageLoadingScripts);
});

Upvotes: 0

Related Questions