views:

38

answers:

1

Hi all,
I'm making a script which has one ajax call inside an each function. The problem is that on the success callback from ajax call, I want to use the object that we are using at each function.

EDIT: Here is some of my code:

configs={
  general:{
    max_ads:6},
  logs:{
    selector:"div#MicrodualGetAd-debug"},
  connection:{
    type:"POST",
    url:"http://www.microdual.com/api/microdualgetad",
    cache:false,
    timeout:20000,
    dataType:"json",
    data:{
      adget_id:null,
      adget_session:null,
      client_action:null},
    error:function(r,s,e){
      MicrodualGetAdLog("Ajax-Error: "+s+"\n");
    }
  }
};


$("div.MicrodualGetAd").each(function(){
  configs.connection.data.adget_id = $(this).attr("rel");
  configs.connection.data.client_action = "view";
  configs.connection.data.success = function(d,s,r){
    $(this).hide();
    alert("'OK'");
    if(d.hackattemp.status){
      MicrodualGetAdLog("MicrodualGetAd-Error: "+d.hackattemp.msg+"\n");
      $(this).append(d.hackattemp.msg);
    }
  }
  $.ajax(configs.connection);
});
+3  A: 

You need to save the value of this just inside your each callback.

$("#hello").each(function() {
    var that = this;

    $.ajax({
        url: "www.mysite.com/mypage",
        success: function(d) {
            hello.call(that);
        }
    });
})​

Also, you should check the value of d differently; either

if (typeof d === 'undefined' && d !== '') ...

or simply

if (d) ...

Edit 1: This should work, assuming the only problem you're having is getting the right value of this:

$("div.MicrodualGetAd").each(function() {
    var $this = $(this);
    configs.connection.data.adget_id = $this.attr("rel");
    configs.connection.data.client_action = "view";
    configs.connection.data.success = function(d, s, r) {
        $this.hide();
        alert("'OK'");
        if (d.hackattemp.status) {
            MicrodualGetAdLog("MicrodualGetAd-Error: " + d.hackattemp.msg + "\n");
            $this.append(d.hackattemp.msg);
        }
    }
    $.ajax(configs.connection);
});​
Matt Ball
i've edited my question to part of my code to you understand. my example was a little bad, sorry.
CuSS
@CuSS - see my edit. There's really not much difference, assuming the rest of your code works.
Matt Ball
It worked... explain me something, why do you put the jQuery var before the var name?
CuSS
Oh forget it, i was assuming that the char $ wasn't part of the var name (like the php programming way). Thanks, correct answer! +1
CuSS
I like to prepend `$` to names of variables that store jQuery objects. It helps me remember exactly what I'm storing.
Matt Ball
good tip ;)thank you again!
CuSS