سؤال

I have an event which calls the jQuery $.post function. I would like to access to a defined variable inside the $.post function and I am having troubles with it.

In this case, I would like to access the currentId variable.

$('.notMatching').click(function(){     
    var currentId = this.id;
    $.post("http://"+ document.domain + baseUrl +"/tables/demo.json",  { id: this.id }, 
            function(dat){

                alert(currentId); //undefined

                if(dat['result']==1){
                    $(this).parent().html('<input type="checkbox" class="first" value="'+this.id+'">');
                }
            }
    );
});

Is there a way to do it?

Btw, this event is inside $(document).ready(function(){ with many other events.

هل كانت مفيدة؟

المحلول

You don't need to do any assignment by making anything global...

    $('.notMatching').click(function(){     

    var that = this
    $.post("http://"+ document.domain + baseUrl +"/tables/demo.json",  { id: this.id }, 
            function(dat){

                alert(that.id);

                if(dat['result']==1){
                    $(this).parent().html('<input type="checkbox" class="first" value="'+that.id+'">');
                }
            }
    );
});

Assign your this variable to that and your that will be accessible within success call back of $.post

نصائح أخرى

Please declare the variable globally!.

var currentId = null;
$('.notMatching').click(function() {
currentId = this.id;
$.post("http://" + document.domain + baseUrl + "/tables/demo.json", {
    id : this.id
}, function(dat) {

    alert(currentId);
    //undefined

    if (dat['result'] == 1) {
        $(this).parent().html('<input type="checkbox" class="first" value="' + this.id + '">');
    }
});

});

the scope inside the callback is changed, you need to preserve it

$('.notMatching').click(function(){     
    var currentId = this.id;
    var that = this;
    if (currentId)
        $.post("http://"+ document.domain + baseUrl +"/tables/demo.json",  { id: currentId }, function(dat){
            if(dat['result']==1)
                $(that).parent().html('<input type="checkbox" class="first" value="'+currentId+'">');
        });
    else 
        alert('No Id');
});
var currentId = null;
var that = this;
$('.notMatching').click(function() {
currentId = this.id;
$.ajax({
  'type' : 'POST',
  'dataType' : 'JSON',
  'data': {'id':currentId},
  'url': "http://" + document.domain + baseUrl + "/tables/demo.json",
  'success': function(response){
    if ((JSON.parse(response)).result === 1) {
      $(this).parent().html('<input type="checkbox" class="first" value="' + that.id + '">');
    }
  }
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top