0

Possible Duplicate:
Jquery: Return the value of a ajax call to caller function?

In the code below ,

I'm trying to put my ajax call in a function that needs it but makeIt() wont return "usa from the ajax call ? Or am I going about this all wrong?

var makeIt = function () {
    var getStuff = function () {
        return $.ajax({
          type: "POST",
          url: "my.php",
          data: {
            id: "2"
          },
          success: function (data) {
            data
          }, // data will return string "usa"
          error: function () {
            alert("error");
          }
        });
      };
    return getStuff();
  };
var result = makeIt() //result should = "usa"
Community
  • 1
  • 1
Hello-World
  • 9,277
  • 23
  • 88
  • 154
  • 2
    AJAX = **Asynchronous** JavaScript and XML ... the `$.ajax()` function doesnt return a value - it executes a `callback` (`success`) once the execution of the remote url is complete ... – Manse Jul 11 '12 at 09:15
  • [Async](https://www.google.com.sg/search?q=define%3Aasynchronous) – Andreas Wong Jul 11 '12 at 09:17
  • 1
    @ManseUK I think you are right - my only concern is that the answer to the question you refer to is saying to use `async:false` witch atleast I think is a bad approach. – Andreas Louv Jul 11 '12 at 09:20
  • @AndreasAL agreed .. perhaps there is a better duplicate ? – Manse Jul 11 '12 at 09:21
  • 1
    posible diplicate: http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success – Andreas Louv Jul 11 '12 at 09:22

3 Answers3

2

Just writing data in the success function doesn't achieve anything.

  success: function (data) {
    data
  }

It needs to be something like

  success: function (data) {
     doSomethingWith(data);
  }
Otto Allmendinger
  • 27,448
  • 7
  • 68
  • 79
2

You're doing it wrong. $.ajax call is anychronous, there is no way for makeIt to return a value obtained by $.ajax call, you can do this instead:

var makeIt = function (callback) {
    $.ajax({
        type: "POST",
        url: "my.php",
        data: { id: "2" },
        success: callback,
        error: function () { alert("error"); }
    });
};

makeIt(function (result) { 
    //result should = "usa"
});  

That way, you'll have a nice wrapper around $.ajax call, with all the parameters and error handling provided.

Tomek
  • 785
  • 4
  • 10
1

Define "result var" as global var.

Then add extra function to your project.

var result;

var makeIt = function () {


    var getStuff = function () {

       return $.ajax({
            type: "POST",
            url: "my.php",
            data: { id: "2" },
            success: function (data) { fnResult(data) },
            error: function () { alert("error"); }
        });


    };

function fnResult(data){result = data};
Kerberos
  • 1,228
  • 6
  • 24
  • 48