2

I have an ajax call in a function and I did not find a solution how to return the data:

function get_blog_post(id){

    var info="id="+id;
    $.ajax({
            type: 'POST',
            url: 'get_blog_post.php',
            data: info,
            success: function(data){
                return data;
            }
    });

}

The code above doesn't works. The data contains the right answer but I can't use it if I callthe get_blog_post() function.

:\

csaron92
  • 1,035
  • 2
  • 10
  • 20
  • 1
    Nope you can't, because the function that invokes the Ajax call completes before the Ajax call finishes. – Andrew Senner Apr 11 '13 at 17:00
  • In success function you send your response data to another js function to process it. [this](http://stackoverflow.com/questions/15945278/how-to-get-json-data-from-the-urlrest-api-to-ui-using-jquery-or-java-script/15945449#15945449) might help you. – Ashish Panery Apr 11 '13 at 17:28

3 Answers3

4
function get_blog_post(id, callback){

    var info="id="+id;
    $.ajax({
        type: 'POST',
        url: 'get_blog_post.php',
        data: info,
        success: function(data){
            callback(data);
        }
    });
}

get_blog_post(5, function(data){
    // use data here
});

OR set async = false (not recommended):

    $.ajax({
        type: 'POST',
        url: 'get_blog_post.php',
        data: info,
        async: false,
        success: function(data){
            return data;
        }
    });
karaxuna
  • 26,752
  • 13
  • 82
  • 117
1

The success function runs some time after the ajax call completes. That's the nature of asynchronous calls--like ajax in javascript.

That means you cant return it and have to do something with the data in that function. Perhaps it is text and you put it into a text area like:

success: function(data){
             $('textarea').val(data);
         }
Lee Meador
  • 12,829
  • 2
  • 36
  • 42
1

Provide a callback method and do what ever you want to do inside it

function get_blog_post(id, callback){

    var info="id="+id;
    $.ajax({
            type: 'POST',
            url: 'get_blog_post.php',
            data: info,
            success: callback
    });

}
Anoop
  • 23,044
  • 10
  • 62
  • 76