I have an AJAX function inside a javascript file and I want it to be abstract and not to use any global variables.
The AJAX inserts an event into a database:
function insertCalendarEvents(calendar_group, event_name, event_datestart, event_datestop, event_timestart, event_timestop, event_info, onFinish) {
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
if(request.responseText.substr(0, 6) == "error ")
alert(errorName[request.responseText.substr(6)]);
else {
var event_id = request.responseText;
//call onFinish function with parameter event_id which database assigned it
}
}
}
request.open("GET", "php/calendar.php?action=insertCalendarEvents&calendar_group=" + calendar_group + "&event_name=" + event_name + "&event_datestart=" + event_datestart + "&event_datestop=" + event_datestop + "&event_timestart=" + event_timestart + "&event_timestop=" + event_timestop + "&event_info=" + event_info, true);
request.send();
}
The function is asynchronous so what I want to do is, at the moment it finished inserting the data into the database, I want it to execute a function which I will give it as a parameter.
If there is a better idea on how to accomplish this, I would be really happy to hear it 🙂
Thank you in advance, Daniel!
Functions are just objects you can pass. The only extra thing is that you can call them using
()(additionally with arguments, of course).You can pass them around just fine; all information such as scoping will be preserved. So, this should work:
Basically, a more trivial example would be this: