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
Your coffeescript renders to:
And you cannot return from an ajax statement. you must use a callback!
So your rendered js code can be changed to: