I've been trying to follow this question which partly has the same problem as I do. The question wants to be able to return the Ajax response. I want to do the same but a bit different I need to use a function with parameters inside the callback?
How can I do this? How can I merge the two so I'm able to return the Ajax request but also still use dynamic parameters?
function foo(callback) {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === 4) { // request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // we're calling our method
}
}
};
httpRequest.open('GET', "/echo/json");
httpRequest.send();
}
foo(function (result) {
alert(result);
});
My Ajax function
var ajax_http,
ajax_url,
ajax_parameters;
function ajax(url, parameters, method, form = false) {
ajax_http = new XMLHttpRequest();
ajax_url = url;
ajax_http.open(method, ajax_url, true);
if (form === false) {
ajax_parameters = parameters;
ajax_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
} else {
ajax_parameters = new FormData(form);
}
ajax_http.onreadystatechange = function () {
if (ajax_http.readyState === 4 && ajax_http.status === 200) {
return this.responseText;
}
};
ajax_http.send(ajax_parameters);
}
How do I combine these two so that I can use my function with parameters inside the callback function?
EDIT - Missing formal parameter
function ajax(callback, url, parameters, method, form = false) {
var ajax_http,
ajax_url,
ajax_parameters;
ajax_http = new XMLHttpRequest();
ajax_url = url;
ajax_http.open(method, ajax_url, true);
if (form === false) {
ajax_parameters = parameters;
ajax_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
} else {
ajax_parameters = new FormData(form);
}
ajax_http.onreadystatechange = function () {
if (ajax_http.readyState === 4 && ajax_http.status === 200) {
callback(ajax_http.responseText);
}
};
ajax_http.send(ajax_parameters);
}
ajax(function (results, "ajax.php", "none", "POST", false) {
alert(results);
});