Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to utilize generic AJAX call with multiple success functions

I am making an ajax call that returns XML. This XML needs to be handled differently based upon the section of the page within the site the user is on. Thus, I would like to implement 1 ajax function that makes the calls, and has a variable success function... I'm sure it is simple but I've searched for a while and cannot figure it out..

function makeAjaxCall(variableSuccessFunction) {
    $.ajax.... (ajax stuff goes here)...
    success: variableSuccessFunction(xml)
}
function ViewOne(xml) {
    //take the XML and update the dom as appropriate
}
function ViewTwo(xml) {
    //take the XML and update the dom as appropriate
}

$(document).ready(function() {
    //be able to call either one of these functions
    makeAjaxCall(ViewOne);
    makeAjaxCall(ViewTwo);

}
like image 888
Chad Avatar asked Oct 06 '22 14:10

Chad


1 Answers

You've basically got it! Just one tweak:

function makeAjaxCall(variableSuccessFunction) {
    $.ajax.... (ajax stuff goes here)...
    success: variableSuccessFunction // no (xml)
}

You're passing around function references. success is passed a reference to variableSuccessFunction (whatever that may be) and will call it just like it would if you had supplied an anonymous function to it. No need to invoke it inside of makeAjaxCall.

like image 58
Andrew Whitaker Avatar answered Oct 10 '22 03:10

Andrew Whitaker