Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing extra arguments to XMLHttpRequest.onload

I'm trying to comunicate with a server, using XMLHttpRequest in javascript.

How can I pass info to the onload function?

// global variable that containts server response
var reply;

var makeRequest = function(extraInfo) {
  var request = new XMLHttpRequest();
  request.open(...);
  request.onload = handler;
};

var handler = function(data) {
  reply = data.target.response;
  console.log("Server Reply: " + reply);
};

How can I pass the parameter extraInfo from makeRequest to the handler function? (without using a global variable)

like image 666
Tirafesi Avatar asked Dec 28 '16 10:12

Tirafesi


People also ask

What does XMLHttpRequest onload do?

The onload Property With the XMLHttpRequest object you can define a callback function to be executed when the request receives an answer.

What is xhr send()?

send() The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived.

How to call API using XMLHttpRequest?

To send an HTTP request, create an XMLHttpRequest object, open a URL, and send the request. After the transaction completes, the object will contain useful information such as the response body and the HTTP status of the result.


2 Answers

Just use a closure in such way:

...
var makeRequest = function(extraInfo) {
    var request = new XMLHttpRequest();
    request.open(...);
    request.onload = function(data) {
        // extraInfo is accessible here
        reply = data.target.response;
        console.log("Server Reply: " + reply);
    };
};
like image 196
hindmost Avatar answered Sep 28 '22 07:09

hindmost


I figured out that passing extra info into the request handler can be done this way: (At least is good for me)

    request.open(...);
    request.extraInfo = identifier;
    request.onload = function() {
        identifier = this.extraInfo;
    };
like image 25
user12448046 Avatar answered Sep 28 '22 06:09

user12448046