NiLL
NiLL

Reputation: 13843

Return variable in JavaScript function

I need to receive a AJAX request value, but alway receive undefined.

Panda.Meals.getMealById = function(id) {
  var meal = {};
  $.ajax({
    url: "http://localhost/admin.php?r=mess/getmealbyid",
    data: {"id": id},
    success: function(data) {
      meal = data;
    }
  });
  return meal;
}

var id = Panda.Meals.getMealById(10);

Upvotes: 0

Views: 128

Answers (3)

Molochdaa
Molochdaa

Reputation: 2218

Your ajax call is asynchronous, so meal is undefined when you return the value.

You can do it like :

Panda.Meals.getMealById = function(id) {
    var meal = {};
    $.ajax({
        async: false,
        url: "http://localhost/admin.php?r=mess/getmealbyid",
        data: {"id": id},
        success: function(data) {
            meal = data;
        }
    });
    return meal;
}

Upvotes: 2

Sjoerd
Sjoerd

Reputation: 75599

The function getMealById does not wait for the result of AJAX request. Since $.ajax does not block, the getMealById function returns before the AJAX request is finished.

Upvotes: 3

Abdul Munim
Abdul Munim

Reputation: 19217

This is an asynchronous call. Your function will return just after calling $.ajax(). You have to provide a callback function to your getMealById.

See this example.

Panda.Meals.getMealById = function(id, callback) {
  $.ajax({
    url: "http://localhost/admin.php?r=mess/getmealbyid",
    data: {"id": id},
    success: function(data) {
       callback(data);
    }
  });
}

Panda.Meals.getMealById(10, function(data) {
   var id = data;
   // do all your post processing here
});

Upvotes: 3

Related Questions