Sorted it, this site helped me get to grips with callbacks - Callback Functions in JavaScript | Impressive Webs
Code:
/***** AJAX */
function ajax(queryMethod, fileURL, successOutputTarget, success, failureOutputTarget, failure, queryURL) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
successOutputTarget.innerHTML = xhttp.responseText;
success(xhttp);
} else {
failureOutputTarget.innerHTML = xhttp.responseText;
failure(xhttp);
}
}
xhttp.open(queryMethod, fileURL, true);
if (queryMethod == 'POST') {
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(queryURL);
} else {
xhttp.send();
}
}
/***** 1st AJAX call */
var searchForm = document.getElementById('searchForm');
var searchTerm = document.getElementById('searchTerm');
searchForm.addEventListener('submit', function(event) {
searchTermValue = encodeURIComponent(searchTerm.value);
var successOutputTarget = document.getElementById('results');
var failureOutputTarget = '';
ajax('POST',
'../model/search.php',
successOutputTarget,
function success() {
activateCopyControl2eventListeners();
tooltips();
reportICD();
},
failureOutputTarget,
function failure() {
// do something here upon failure
},
'searchTerm=' + searchTermValue);
});
Had to set up parameters for output targets because referencing xhttp inside the ajax() call returned xhttp as undefined.