How to pass context in jquery ajax success callback function

JavascriptJquery

Javascript Problem Overview


var Box = function(){
	this.parm = {name:"rajakvk",year:2010};
	Box.prototype.jspCall = function() {
		$.ajax({
			type: "post",
			url: "some url",
			success: this.exeSuccess,
			error: this.exeError,
			complete: this.exeComplete
		});
	}
	this.exeSuccess = function(){
		alert(this.parm.name);
	}
}

I'm not getting Box object inside exeSuccess method. How to pass Box object inside exeSuccess method?

Javascript Solutions


Solution 1 - Javascript

Use the context option, like this:

    $.ajax({
        context: this,
        type: "post",
        url: "some url",
        success: this.exeSuccess,
        error: this.exeError,
        complete: this.exeComplete
    });

The context option determines what context the callback is called with...so it determines what this refers to inside that function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrajakvkView Question on Stackoverflow
Solution 1 - JavascriptNick CraverView Answer on Stackoverflow