EmFeld
EmFeld

Reputation: 227

Coffeescript $.ajax result shown as undefind

I work with a front-end framework and want to render a page. To do that I use an initializer that calls a function performing $.ajax call to the backend. However, though in chrome dev tools the request is successful, everytime I do console.log it returns undefined. The backend sends the right result but it's not shown.

  initialize: =>
    @build_recent()
    @payload=@recent_data
    console.log(@payload)

  render: =>
    $(@el).append homeTemplate(@payload)
    @

  build_recent: =>
    $.ajax(
      url: '/build_recent'
      dataType: 'text/json'
      type: 'GET'
      success: (data) =>
        @recent_data = data
    )

Update:

simply only using render() not using intialize and another function, I finally solved the problem this way:

  render: =>
    $.ajax(
      url: '/build_recent/'
      dataType: 'json'
      type: 'GET'
      success: (data) =>
        @payload = data
        $(@el).append homeTemplate(@payload)
        return @
    )

it turns out that the problem was only this dataType: 'json' previously I use dataType: 'text/json'

now it works out fine

Upvotes: 0

Views: 1109

Answers (1)

Naftali
Naftali

Reputation: 146310

Your coffeescript renders to:

var _this = this;

({
  initialize: function() {
    _this.build_recent();
    _this.payload = _this.recent_data;
    return console.log(_this.payload);
  },
  render: function() {
    $(_this.el).append(homeTemplate(_this.payload));
    return _this;
  },
  build_recent: function() {
    return $.ajax({
      url: '/build_recent',
      dataType: 'text/json',
      type: 'GET',
      success: function(data) {
        return _this.recent_data = data;
      }
    });
  }
});

And you cannot return from an ajax statement. you must use a callback!

So your rendered js code can be changed to:

({
  initialize: function() {
    _this.build_recent();
    //moved into callback
  },
  render: function() {
    $(_this.el).append(homeTemplate(_this.payload));
    return _this;
  },
  build_recent: function() {
    return $.ajax({
      url: '/build_recent',
      dataType: 'text/json',
      type: 'GET',
      success: function(data) {
        _this.recent_data = data;
        //in callback
        _this.payload = _this.recent_data;
        console.log(_this.payload);
        //prob want to render:
        _this.render();
      }
    });
  }
});

Upvotes: 3

Related Questions