0

I have a JS function which is called in order to fetch the list of titles of posts in a particular month. The data is returned as JSON object. I wish to return the data to the calling function. The response is of the form:

{
  "success":true,
  "days":[
     {
        "date":"2,March 2013",
        "posts":[
           {
              "post_id":"10",
              "post_title":"tgfkyhhj",
              "created_on":"2013-03-02 21:24:17",
              "time":"09:24 PM"
           }
        ]
     } 
  ] 
}

I wish to return the days part of this JSON.

The function is as follows :

function archivePostMonth(month) {
    var days; 
    $.ajax({
        'type' : 'get',
        'url' : base_url + 'index.php/blog/blogArchiveMonth',
        'data' : {
            'blogId' : blogId,
            'month' : month,
        },
        success : function(response) {
            var res = jQuery.parseJSON(response);
            if (res.success == true) {
                console.log(res.days); //displays the data
                days = res.days;
                console.log(days); // displays the data
            }
        }
    });
    console.log(days); //undefined
    return days; // returns undefined
}

No matter what the function returns undefined. I can't figure out the problem. Is there a better way to do this ?

luiges90
  • 4,493
  • 2
  • 28
  • 43
mlakhara
  • 235
  • 3
  • 11

1 Answers1

1

ajax is asynchronous so, in your code, you are performing a request to the server AND returning the value of days (a variable with an undefined value) at the same time.

The variable days does not have a value until your success callback is called which happens AFTER your function has already returned undefined.

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100