1

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);
});
Robert Wade
  • 4,918
  • 1
  • 16
  • 35
ii iml0sto1
  • 1,654
  • 19
  • 37
  • You could return just the callback being an array. So callback['url'] returns you the url, callback['parameters'] return you the parameters, etc. – David Dutra Dec 14 '17 at 11:20
  • Im not quite sure what you mean by this, how does this allow me to use paramters for the ajax call? :) – ii iml0sto1 Dec 14 '17 at 11:23
  • I'm afraid I can't follow what you're asking for. Are you asking how to pass `ajax` a callback? How to call that callback with multiple arguments? ...? (BTW: Major issue with that `ajax` function as written. Those variables outside it should be *inside* it so they're specific to each call, not reused.) Also note that `return this.responseText;` won't do anything useful inside the `onreadystatechange` handler. – T.J. Crowder Dec 14 '17 at 11:24
  • Why is that a major issue with the variables? Also yes i want to use the callback with multiple arguments :) – ii iml0sto1 Dec 14 '17 at 11:26
  • @iiiml0sto1: Two issues: 1. Each call to `ajax` overwrites those variables, even if the previous call hasn't completed. 2. There's no reason to keep the XHR object once everything is done. – T.J. Crowder Dec 14 '17 at 11:29
  • Thats a fair argument, im still very new to programming and i fight quite alot with how to structure the code exactly :) is this generally a bad idea? cause its something ive began to do quite a bit but thats not for async calls? – ii iml0sto1 Dec 14 '17 at 11:32
  • Ive read somewhere that its better to do a reference than making all new variables all the time ? – ii iml0sto1 Dec 14 '17 at 11:32
  • @iiiml0sto1: In general, scope your variables as narrowly as you can. That means declaring them in the innermost scope possible (inside your function, in this case). *"Ive read somewhere that its better to do a reference than making all new variables all the time ?"* All due respect, I think maybe you misread that. :-) – T.J. Crowder Dec 14 '17 at 11:33
  • Okay i will keep that in mind and study a bit on the variable reference. One quick question, can i not return true/false and check for that? it seems to give me some problems – ii iml0sto1 Dec 14 '17 at 13:34

2 Answers2

1

To pass the callback multiple arguments, you just...do that when calling it:

function ajax(callback, url, parameters, method, form = false) {
//            ^^^^^^^^---- *** accept a callback
    var ajax_http,            // *** These should be locals
            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) {
            // *** Call the callback
            callback(ajax_http.responseText, anything, else, here, you, like);
        }
    };
    ajax_http.send(ajax_parameters);
}

So for instance, if you wanted to echo back the URL:

callback(ajax_http.responseText, url);

...or all of the ajax parameters:

callback(ajax_http.responseText, url, parameters, method, form);

...etc.


Re the "missing formal parameter" error, this is incorrect:

ajax(function (results, "ajax.php", "none", "POST", false) {
    alert(results);
});

You're trying to use "ajax.php" (and such) as parameters, not arguments. Instead:

ajax(function(results) {
    alert(results);
}, "ajax.php", "none", "POST", false);

Or if you move callback to the end of ajax's parameter list:

function ajax(url, parameters, method, form, callback) {

...then you'd call it with the function at the end:

ajax("ajax.php", "none", "POST", false, function(results) {
    alert(results);
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Assuming you want to use parameters inside your

ajax_http.onreadystatechange = function () {
    if (ajax_http.readyState === 4 && ajax_http.status === 200) {
        return this.responseText;
    }
};

function, there's nothing to stop you from simply using parameters in there like so:

ajax_http.onreadystatechange = function () {
    console.log(parameters) //Parameters works here!
    if (ajax_http.readyState === 4 && ajax_http.status === 200) {
        console.log(parameters) //Parameters works here too!
        return this.responseText;
    }
};

If this is not what you mean, please let me know

Glitcher
  • 1,078
  • 6
  • 14