Give the following Ajax call in jQuery:
{
.
.
.
,
getSomeData: function(args, myUrl, foo) {
$.ajax( {
type: \"GET\",
url:
If you declare myHandler
within the request, you can use a closure.
getSomeData: function(args, myUrl, foo) {
$.ajax( {
type: "GET",
url: myUrl,
data: args,
async: true,
dataType: 'json',
success: function (data, textStatus, oHTTP){ ... }
});
},
this way, foo
will be available to you inside the success
callback.
@Unicron had the right answer but didn't give a good example. Check this out:
$( 'tr.onCall' ).on( 'click', function( event ) {
let pEvent = function() { return event; } // like a fly in amber...
$.ajax( {
...
success: function( data ) {
let x = pEvent(); // x now equals the event object of the on("click")
}
});
});
By declaring the pEvent function inside the anonymous function that fires on("click")
, the event object is "frozen" (encapsulated) in its original context. Even when you call it in the different context of the ajax success function, it retains its original context.
More specific example: I'm going to open a modal dialog (styled Div) on click, but when the dialog is closed I want to return the focus to the element that was clicked to open it in the first place...
$( 'tr.onCall' ).on( 'click', function( event ) {
let rTarget = function() { return event.currentTarget; }
$.ajax( {
url: 'ajax_data.php',
...other settings...
success: function( data ) {
modal_dialog(
data,
{
returnTarget: rTarget(),
...other settings...
}
);
}
});
});
On success, it calls a custom function modal_dialog()
(defined elsewhere), passing in an object containing various settings. The returnTarget
setting contains the HTML ID attribute of the element that was clicked; so when I close the dialog I can run $(options.returnTarget).focus();
to return focus to that element.
If you're $.ajax call is in a class and the success callback is passed a method of that class, it does not work.
EDIT: Here is the answer. Note that I am defining the function ajaxCall as a method in a class. I define this.before, this.error, and this.success as methods of ajaxCall because they can call methods from the superClass.
function main(url){
this.url = url;
this.ajaxCall = function(){
this.before = function(){
//Can call main class methods
};
this.error = function(){
//Can call main class methods
};
this.success = function(data){
//Can call main class methods
};
//This is how you pass class arguments into the success callback
var that = this;
$.ajax({
url: this.url,
type: 'GET',
dataType: 'json',
beforeSend: this.before(),
error: this.error(),
success: function(data){that.succes(data);}
});
//Run internally by calling this.ajaxCall() after it is defined
//this.ajaxCall();
}
//Or externally
var main = new main(SOME_URL);
main.ajaxCall();