I’m having issues with some code I’m working on. I have a generic function (ajaxContent) that is used from several points. What I need for this is a to run a function after the AJAX call has been made, but I need to pass though some data that I have before I made the call (so not data that comes back from the AJAX call.
function ajaxContent(url, id, target, data, callbackFunction) {
$.ajax({
async : true,
....
complete: function(){
if(typeof callbackFunction == "function"){
callbackFunction(); // function get's executed here, lead_id is not available
}
}
});
}
$(document).on("click", "#something", function(){
var leaf_id = $(this).attr('rel');
ajaxContent(url, id, target, data, function(leaf_id){
url = "/path/" + leaf_id;
window.location = url;
})
})
$(document).on("click", "#action", function() {
ajaxContent(url, id, target, data, function(){
if ($(this).attr('rel') == "M_0") // $(this).attr('rel') not available here, so need to pass through some way
$('#treedata').css('background', 'url(/img/rotonde.png) 50% 50% no-repeat');
});
});
I could perhaps use somehing like
function ajaxContent(url, id, target, data, callbackFunction, varA, varB, varC, varD) {
callbackFunction(varA, varB, varC, varD);
}
with
ajaxContent(url, id, target, data, function(varA){
}, varA, varB, varC, varD)`
But not really scalable.
I hope this is clear 🙂
In the code you have in your answer now,
leaf_idis a local variable inside thedocument.ready()handler function. As such, it is not available outside that context.You have several choices to fix that:
You can move the definition of ajaxContent function inside the
document.ready()handler function so that it will be able to see leaf_id.You can make
leaf_ida global variable so it can be accessed from anywhere.You can pass
leaf_idto ajaxContent as a function argument.Without more context about what you’re doing, and because this is a transient value that is associated only with the particular action, I think the best option is #3:
Or, if you have lots of variables to pass through, you can create an empty object and then put each variable as a property on that object and then just pass the single object into ajaxContent and into your callback like this:
Note, in my code example, I named the argument something different than the other variable to avoid confusion about which is which.