2

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);
});
cusspvz
  • 5,143
  • 7
  • 30
  • 45

1 Answers1

4

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
  • 354,903
  • 100
  • 647
  • 710
  • i've edited my question to part of my code to you understand. my example was a little bad, sorry. – cusspvz Aug 30 '10 at 14:23
  • @CuSS - see my edit. There's really not much difference, assuming the rest of your code works. – Matt Ball Aug 30 '10 at 14:27
  • It worked... explain me something, why do you put the jQuery var before the var name? – cusspvz Aug 30 '10 at 14:29
  • 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 – cusspvz Aug 30 '10 at 14:30
  • 1
    I like to prepend `$` to names of variables that store jQuery objects. It helps me remember exactly what I'm storing. – Matt Ball Aug 30 '10 at 14:32