1
var pload = function(ctrl, func){
    var dataa;
    $.post("/index.php/"+ctrl+"/"+func,{}, function(data){
    dataa = data;
    });
    return dataa;
};

var bind = function(hashtag, ctrl, func, div){
    $(document).on("click", "a[href="+hashtag+"]", function() {
            var body = pload(ctrl, func);
             alert(body);
            $(div).html(body);
    })
}

How I can get data in global? I want, so pload return data from post request. But I get "undefined" in alert()

  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Guilherme Sehn Jan 09 '14 at 11:25
  • This question was already asked a lot of times here in Stack Overflow. Take a look at the link above, it really will make you understand why it's not working. – Guilherme Sehn Jan 09 '14 at 11:29

3 Answers3

2

Try using callback.

function pload(ctrl, func,callback){
    $.post("/index.php/"+ctrl+"/"+func,{}, function(data){
        callback(data);
    });
};

var bind = function(hashtag, ctrl, func, div){
    $(document).on("click", "a[href="+hashtag+"]", function() {
        pload(ctrl, func,function(body){
            alert(body);
            $(div).html(body);
        });             
    })
}
Hiral
  • 14,954
  • 11
  • 36
  • 57
0

tyr this:

var pload = function(ctrl, func){
    var dataa;
    $.post("/index.php/"+ctrl+"/"+func,{}, function(data){
    dataa = data;
    return dataa;
    });

};
asdf_enel_hak
  • 7,114
  • 3
  • 36
  • 77
  • Will that cause the function `pload` to return `dataa`? I think it will cause the function that is called when the async call finishes to return `dataa` instead. – Timothy Groote Jan 09 '14 at 11:29
0

You're not getting any value back because $.post is asynchronous, and won't halt the program until it receives a value back.

You should move the data handling portion to the function which will be called when the async call returns its result.

var pload = function(ctrl, func){
    var dataa;
    $.post("/index.php/"+ctrl+"/"+func,
      {}, 
      //this function will be called when $.post receives its response
      function(data){
        alert(data);
        $(div).html(data);
      });
    return dataa;
};
Timothy Groote
  • 8,303
  • 25
  • 52