Chris Sobolewski
Chris Sobolewski

Reputation: 12935

Passing a callback and other parameters to jQuery ajax success?

I wrote a function which I'm allowing a callback to be passed to. I then want to execute that with both the ajax repsonse, and another parameter.

My problem is the the callback is executed, and when I step through the code, it looks like the function is called with the proper parameters, however when actually stepping in to the callback function, the first parameter takes the value of whatever I assign to the second argument, and the second argument is undefined.

Here is my function:

namespace = {
fetch : function(sr, count, callback) {
    srCount = count ? count : '25'
    var sub;
    if (sr == 'frontpage'){
        sub = '';
    }else{
        sub = 'foo/' + sr + '/';
    };
    $.ajax({
        url: "http://www.example.com/"+sub+ ".json?count=" + count,
        dataType: "json",
        success: function(msg)
        {
            callback.call(msg, count)
        }
    })
};

Now, when I call it like this:

mynamespace.fetch($(this).attr('href'), 25, true, another namespace.createPost);

I would expect callback.call(msg, count) to resolve to callback.call(/*the ajax response*/, 25);

However, when I run it, I get msg == 25 and count == 'undefined'. I'm at a loss for why...

Upvotes: 1

Views: 1670

Answers (2)

techfoobar
techfoobar

Reputation: 66663

$.ajax() function has a context parameter, which you can use for this purpose.

$.ajax({
  url: "http://www.example.com/"+sub+ ".json?count=" + count,
  context: "hello",
  dataType: "json",
  success: function(msg)
  {

    // here 'this' will be the 'hello' you specified for context while making the call.

    callback.call(msg, count)
  }
})

Upvotes: 1

Esailija
Esailija

Reputation: 140230

.call calls a function with explicit context given by the first argument, so callback.call(msg, count) calls the callback function with msg set as context (the this value inside the callback function for this call) and count as a first argument.

So you probably want callback( msg, count ) or callback.call( namespace, msg, count ); which means that this inside the callback will refer to namespace for that call.

Upvotes: 4

Related Questions