5

I've searched for this and can't seem to find an successful answer, I'm using a jQuery ajax call and I can't get the response out to the callback.

Here's my coffeescript code:

initialize: (@blog, @posts) ->
    _url = @blog.url
    _simpleName = _url.substr 7, _url.length
    _avatarURL = exports.tumblrURL + _simpleName + 'avatar/128'
    $.ajax
        url: _avatarURL
        dataType: "jsonp"
        jsonp: "jsonp"
        (data, status) => handleData(data)

handleData: (data) =>
    console.log data
    @avatar = data

Here's the compiled JS:

  Blog.prototype.initialize = function(blog, posts) {
    var _avatarURL, _simpleName, _url,
      _this = this;
    this.blog = blog;
    this.posts = posts;
    _url = this.blog.url;
    _simpleName = _url.substr(7, _url.length);
    _avatarURL = exports.tumblrURL + _simpleName + 'avatar/128';
    return $.ajax({
      url: _avatarURL,
      dataType: "jsonp",
      jsonp: "jsonp"
    }, function(data, status) {
      return handleData(data);
    });
  };

  Blog.prototype.handleData = function(data) {
    console.log(data);
    return this.avatar = data;
  };

I've tried a dozen variations and I can't figure out how to write this?

Thanks.

2 Answers 2

2

Your arguments are incorrect, you are passing the callback as the second parameter to $.ajax. You should pass it as success: in the options, or add it to the Ajax deferred object.

Since handleData looks like it is attached to an object, which is likely this, you need to prefix it with @.

While your way of passing the URL works, the API now suggests passing the URL as the first param and the options as the second.

$.ajax _avatarURL,
  dataType: "jsonp"
  jsonp: "jsonp"
  success: (data, status) => @handleData(data)

OR

$.ajax _avatarURL,
  dataType: "jsonp"
  jsonp: "jsonp"
.done (data) => @handleData(data)
Sign up to request clarification or add additional context in comments.

3 Comments

same here handleData never gets called it just returns a method, not the return of handleData
Sorry, what returns a method? initialize? To be clear, at the moment initialize will return a jQuery jqXHR object. api.jquery.com/Types/#jqXHR. There data is not returned.
Sorry, you were right, I just needed another cup of coffee. ;-)
2

Since handleData is in Blog's prototype, not a variable in scope, you probably want this:

(data, status) => @handleData(data)

1 Comment

the method never gets executed it just returns the method handleData not the actual return of that method.

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.