Search code examples
javascriptjquery.postjquery-post

Accessing a variable inside $.post jQuery


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.


Solution

  • 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