0

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);
0

3 Answers 3

3

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
});
Sign up to request clarification or add additional context in comments.

4 Comments

+1 Good example, but I believe in this case you can just write success: callback instead of success: function(data){callback(data);}.
Yeah, that would do too, if don't need any decoration on response data
Yes, like in this case. If OP ever needs any, then he will need to use the success callback definition given by you.
Yeah, that would be his sole choice
3

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.

Comments

2

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;
}

1 Comment

Generally, because of how JavaScript works, the better idea is to use callbacks instead of relying on synchronous AJAX calls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.