Quantcast
Channel: How do I return the response from an asynchronous call? - Stack Overflow
Viewing all articles
Browse latest Browse all 46

Answer by cocco for How do I return the response from an asynchronous call?

$
0
0

XMLHttpRequest 2 (first of all, read the answers from Benjamin Gruenbaum and Felix Kling)

If you don't use jQuery and want a nice short XMLHttpRequest 2 which works in the modern browsers and also in the mobile browsers, I suggest to use it this way:

function ajax(a, b, c){ // URL, callback, just a placeholder  c = new XMLHttpRequest;  c.open('GET', a);  c.onload = b;  c.send()}

As you can see:

  1. It's shorter than all other functions Listed.
  2. The callback is set directly (so no extra unnecessary closures).
  3. It uses the new onload (so you don't have to check for readystate && status)
  4. There are some other situations, which I don't remember, that make the XMLHttpRequest 1 annoying.

There are two ways to get the response of this Ajax call (three using the XMLHttpRequest var name):

The simplest:

this.response

Or if for some reason you bind() the callback to a class:

e.target.response

Example:

function callback(e){  console.log(this.response);}ajax('URL', callback);

Or (the above one is better anonymous functions are always a problem):

ajax('URL', function(e){console.log(this.response)});

Nothing easier.

Now some people will probably say that it's better to use onreadystatechange or the even the XMLHttpRequest variable name. That's wrong.

Check out XMLHttpRequest advanced features.

It supported all *modern browsers. And I can confirm as I have been using this approach since XMLHttpRequest 2 was created. I never had any type of problem in any browsers I used.

onreadystatechange is only useful if you want to get the headers on state 2.

Using the XMLHttpRequest variable name is another big error as you need to execute the callback inside the onload/oreadystatechange closures, or else you lost it.


Now if you want something more complex using POST and FormData you can easily extend this function:

function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val},placeholder  c = new XMLHttpRequest;  c.open(e||'get', a);  c.onload = b;  c.send(d||null)}

Again ... it's a very short function, but it does GET and POST.

Examples of usage:

x(url, callback); // By default it's GET so no need to setx(url, callback, 'post', {'key': 'val'}); // No need to set POST data

Or pass a full form element (document.getElementsByTagName('form')[0]):

var fd = new FormData(form);x(url, callback, 'post', fd);

Or set some custom values:

var fd = new FormData();fd.append('key', 'val')x(url, callback, 'post', fd);

As you can see, I didn't implement sync... it's a bad thing.

Having said that ... why don't we do it the easy way?


As mentioned in the comment, the use of error && synchronous does completely break the point of the answer. Which is a nice short way to use Ajax in the proper way?

Error handler

function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val}, placeholder  c = new XMLHttpRequest;  c.open(e||'get', a);  c.onload = b;  c.onerror = error;  c.send(d||null)}function error(e){  console.log('--Error--', this.type);  console.log('this: ', this);  console.log('Event: ', e)}function displayAjax(e){  console.log(e, this);}x('WRONGURL', displayAjax);

In the above script, you have an error handler which is statically defined, so it does not compromise the function. The error handler can be used for other functions too.

But to really get out an error, the only way is to write a wrong URL in which case every browser throws an error.

Error handlers are maybe useful if you set custom headers, set the responseType to blob array buffer, or whatever...

Even if you pass 'POSTAPAPAP' as the method it won't throw an error.

Even if you pass 'fdggdgilfdghfldj' as formdata it won't throw an error.

In the first case the error is inside the displayAjax() under this.statusText as Method not Allowed.

In the second case, it simply works. You have to check at the server side if you passed the right post data.

Cross-domain not allowed throws an error automatically.

In the error response, there aren't any error codes.

There is only the this.type which is set to error.

Why add an error handler if you totally don't have any control over errors?Most of the errors are returned inside this in the callback function displayAjax().

So: There isn't any need for error checks if you're able to copy and paste the URL properly. ;)

PS: As the first test I wrote x('x', displayAjax)..., and it totally got a response...??? So I checked the folder where the HTML is located, and there was a file called 'x.xml'. So even if you forget the extension of your file XMLHttpRequest 2 WILL FIND IT. I LOL'd


Read a file synchronous

Don't do that.

If you want to block the browser for a while load a nice big .txt file synchronous.

function omg(a, c){ // URL  c = new XMLHttpRequest;  c.open('GET', a, true);  c.send();  return c; // Or c.response}

Now you can do

 var res = omg('thisIsGonnaBlockThePage.txt');

There is no other way to do this in a non-asynchronous way. (Yeah, with setTimeout loop... but seriously?)

Another point is... if you work with APIs or just your own list's files or whatever you always use different functions for each request...

Only if you have a page where you load always the same XML/JSON or whatever you need only one function. In that case, modify a little the Ajax function and replace b with your special function.


The functions above are for basic use.

If you want to extend the function...

Yes, you can.

I'm using a lot of APIs and one of the first functions I integrate into every HTML page is the first Ajax function in this answer, with GET only...

But you can do a lot of stuff with XMLHttpRequest 2:

I made a download manager (using ranges on both sides with resume, filereader, and filesystem), various image resizers converters using canvas, populate web SQL databases with base64images and much more...

But in these cases you should create a function only for that purpose... sometimes you need a blob, array buffers, you can set headers, override mimetype and there is a lot more...

But the question here is how to return an Ajax response... (I added an easy way.)


Viewing all articles
Browse latest Browse all 46

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>