Give the following Ajax call in jQuery:
{
.
.
.
,
getSomeData: function(args, myUrl, foo) {
$.ajax( {
type: \"GET\",
url:
@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.