0

Is it possible to return the value of a jquery post into a normal js function like that ?

function get_err(req) {
    var error = $.post("get_err.php", { error: req },
    function(data) { return data; }, "text");
}

If I set alert(data); it's working, but i don't need it to be alerted, i need it to be returned so i can use it like here:

success: function(data) {
   $("#error").html(get_err(data));
}
Eduard
  • 3,395
  • 8
  • 37
  • 62
  • possible duplicate of [jQuery: Return data after ajax call success](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success) – Felix Kling Aug 10 '11 at 08:54

1 Answers1

1

There are three approaches:

  1. Make synchronous request. It is not recommended, so I'll not describe it in more detail

  2. Use 'handler' function, like this:

    $.post("get_err.php", 
        { error: req },
        function(data) {handle_result(data) },
        "text"
    );
    
    function handle_result(data){
        //do whatever you need with result here
    }
    
  3. Use deferred objects. This is relatively new jQuery feature, and I've not mastered it yet, so I'm not sure about the example.

    var deferred = $.ajax({/*ajax params here*/});
    deferred.done([handler1, handler2], handler3); //all handlers are chained and invoke one after another
    //at some moment later or on event//
    deferred.resolve(); //this calls the handlers.
    
    function handler1(data){};
    function handler2(data){};
    function handler3(data){};
    
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
J0HN
  • 26,063
  • 5
  • 54
  • 85