views:

508

answers:

3

When the form is submitted, I'm calling a function getPosts and passing through a variable str. What I'd like to do is get the data returned from that function.

 // when the form is submitted
 $('form#getSome').submit(function(){
  var str = $("form#getSome").serialize();
  var something = getPosts(str);

  * This is where I'd like to get the data returned from getPosts()

  return false;
 });

 // get the data
 function getPosts(str){

     $.getJSON('http://myurl.com/json?'+str+'&callback=?',
       function(data) {

          arrPosts = new Array();

           $.each(data.posts, function(i,posts){

             // build array here

           });

     return arrPosts;

       });
 };

I've tried many things, but have only gotten 'undefined' returned. I've tried console.log(something);, console.log(getPosts).

I'm missing something very fundamental here. Any help would be greatly appreciated.

EDIT:

What I'm trying to do is create a single function that would get posts. Then different events would call that function. I could then use that data. So one event may be submitting a form, another may be clicking a link, another lazy/endless scrolling. All could use the same getPosts function.

There's a lot of parsing out the results which amounts to a lot of lines of code. Was just trying to find a way to reuse that function. Do you think that would be possible?

$('a.thisLink').click(function(){
    getPosts();
    get the return from getPosts() and do something with it
});

$('form.thisForm').submit(function(){
    getPosts();
    get the return from getPosts() and do something with it
});

function getPosts(){
   get the posts and return an array
}
A: 

Your getPosts function looks incomplete, I'm no jquery expert but should it look something like:

function getPosts(str) {

  $.getJSON('http://myexample.com/json?'+str+'&callback=?',function(data){

    var arrPosts = [];

    $.each(data.posts, function(i,posts){
     ... build array yada yada ...
    });

    return arrPosts;

  });
}
camomileCase
+2  A: 

Ajax requests are executed asynchronously, the callback function (function (data)) of getJSON is executed when the request ends, and returning a value in that callback has no effect, because is a nested function inside getPosts and its return value is never used.

Actually in your example, getPosts doesn't return anything and it ends its execution before the data is returned.

I would recommend you to work on your submit event handler, if you want to keep the getPosts function, you can introduce a callback parameter:

$('form#getSome').submit(function(){
  var str = $("form#getSome").serialize();

  getPosts(str, function (data) {
    var array = [];
    $.each(data.posts, function(i,posts){
      // build array here
      array.push(/* value to add */);
    });
    // array ready to work with...
    //...
  });
  return false;
});

function getPosts(str, callback){
  $.getJSON('http://myurl.com/json?'+str+'&callback=?', callback);
}


Edit 2: In response to your second comment, you could make another callback, that will be executed when the data has been processed by the first callback, and you can define it when you execute the getPosts function on the submit event handler:

$('form#getSome').submit(function(){
  var str = $("form#getSome").serialize();

  getPosts(str, reusableCallback, function (result) {
    // result contains the returned value of 'reusableCallback' <---
  });
  return false;
});

function reusableCallback(data) {
  var array = [];
  $.each(data.posts, function(i,posts){
    array.push(/* value to add */);
  });
  //...
  return array;
}

function getPosts(str, callback, finishCallback){
  $.getJSON('http://myurl.com/json?'+str+'&amp;callback=?', function (data) {
    finishCallback(callback(data)); // pass the returned value
                                    // of callback, to 'finishCallback' which is
                                    // anonymously defined on the submit handler
  });
}


Edit 3: I think that the getPosts function and the "reusableCallback" function are strongly related, you might want to join them, and make the code easier to use and understand:

$('form#getSome').submit(function(){
  var str = $("form#getSome").serialize();

  getPosts(str, function (result) {
    // result contains the processed results
  });

  return false;
});


function getPosts(str, finishCallback){
  $.getJSON('http://myurl.com/json?'+str+'&amp;callback=?', function (data) {
    // process the results here
    var array = [];
    $.each(data.posts, function(i,posts){
      array.push(/* value to add */);
    });
    //...
    finishCallback(array); // when the array is ready, execute the callback 
  });
}
CMS
I think this is on the right track. What I was trying to do was create a single function that would get posts. And then different events would get posts. So one event may be submitting a form, another may be clicking a link, another lazy scrolling. All could use the same getPosts function. There's a lot of parsing out the results which amounts to a lot of lines of code. Was just trying to find a way to reuse that. Do you think that would be possible?
jyoseph
Yeah this is exactly what I'm looking for, this way I can keep reusing the reusableCallback function. Last question, how do I reference the data that gets returned (from reusableCallback function) within the submit function?
jyoseph
@jyoseph: Look my second edit...
CMS
Thank you so much. That's exactly what I need. Now I'm going to go study up to make sure I understand why that fully works. Although I know many of the ins and outs of jQuery my javascript is pretty weak, as you can see.Thanks again!
jyoseph
A: 

The problem is that the $.getJSON callback function gets called when the get request returns the data, not inline with your function.

John Boker