0

I'm trying to fetch an object from a local api in the same project, but the product variabel is always undefined after the ajax call.

I don't get any error message from the ajax call, it returns to the success function and executes the different log commands. I thought it was an issue with decimals so I changed them to string, but same result. I've started out using $.getJSON, but changed to $.ajax just to see if that solved it.

GetProduct in _JS.js:

GetProduct: function (id) {
    this.Log("JS GetProduct. Id: " + id);

    $.ajax({
        url: this.apiBaseUrl + "GetProduct?id=" + id,
        dataType: 'json',
        success: function (data) {
            _JS.Log("Product fetched");
            _JS.LogInfo(data);

            return data;
        },
        error: function (xhr, status, error) {
            _JS.LogError(error);
        }
    });
}

The call to GetProduct:

var product = _JS.GetProduct(productId); 

(after this line the product is undefined, but nothing indicates why)

The json result:

{
  "id": 1,
  "name": "Navn pƄ norsk som er ganske langt",
  "description": "Norsk forklaring",
  "price": 11,
  "subscriptionPrice": "9,90",
  "subscriptionDiff": "1,10",
  "priceFormated": "kr. 11,-",
  "subscriptionPriceFormated": "kr. 9,90,-",
  "subscriptionPriceDiffFormated": "kr. 1,10,-",
  "isSubscription": 1
}

I don't have this problem with any other of the ajax calls to the same api (different methods).

SteinTheRuler
  • 3,549
  • 4
  • 35
  • 71
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – James Thorpe Aug 22 '17 at 14:12

1 Answers1

0

I can't comment because of too low reputation so I have to write an answer.

You're making an asynchronous call and therefore you won't get any result by the typical way of synchronous javascript calls.

I try to explain why: You send a request to the server. That request is handled asynchronous so your code will be executed regardless if the response was already sended or not. Because your JS-Code is faster than the response from the server you will get undefined. (Imagine the server is extremely slow and the answer takes several minutes).

The most common way to face this problem is to use either callbacks or promises. See How do I return the response from an asynchronous call?

JoMo
  • 1
  • 1
  • yes thanks. I see what I'm doing wrong. I thought the success function got invoked at the end of the call. – SteinTheRuler Aug 22 '17 at 14:39
  • _"I can't comment because of too low reputation so I have to write an answer."_ -> Please see [Why do I need 50 reputation to comment? What can I do instead?](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). – James Thorpe Aug 22 '17 at 14:51