Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong><a href="http://en.wikipedia.org/wiki/XMLHttpRequest" rel="noreferrer">XMLHttpRequest</a> 2</strong> (first of all read the answers from Benjamin Gruenbaum &amp; Felix Kling)</p> <p>If you don't use jQuery and want a nice short XMLHttpRequest 2 which works on the modern browsers and also on the mobile browsers I suggest to use it this way:</p> <pre><code>function ajax(a, b, c){ // URL, callback, just a placeholder c = new XMLHttpRequest; c.open('GET', a); c.onload = b; c.send() } </code></pre> <p>As you can see:</p> <ol> <li>It's shorter than all other functions Listed.</li> <li>The callback is set directly (so no extra unnecessary closures).</li> <li>It uses the new onload (so you don't have to check for readystate &amp;&amp; status)</li> <li>There are some other situations which I don't remember that make the XMLHttpRequest 1 annoying.</li> </ol> <p>There are two ways to get the response of this Ajax call (three using the XMLHttpRequest var name):</p> <p>The simplest:</p> <pre><code>this.response </code></pre> <p>Or if for some reason you <code>bind()</code> the callback to a class:</p> <pre><code>e.target.response </code></pre> <p>Example:</p> <pre><code>function callback(e){ console.log(this.response); } ajax('URL', callback); </code></pre> <p>Or (the above one is better anonymous functions are always a problem):</p> <pre><code>ajax('URL', function(e){console.log(this.response)}); </code></pre> <p>Nothing easier.</p> <p>Now some people will probably say that it's better to use onreadystatechange or the even the XMLHttpRequest variable name. That's wrong.</p> <p>Check out <a href="http://caniuse.com/xhr2" rel="noreferrer">XMLHttpRequest advanced features</a></p> <p>It supported on all *modern browsers. And I can confirm as I'm using this approach since XMLHttpRequest 2 exists. I never had any type of problem on all browsers I use.</p> <p>onreadystatechange is only useful if you want to get the headers on state 2.</p> <p>Using the <code>XMLHttpRequest</code> variable name is another big error as you need to execute the callback inside the onload/oreadystatechange closures else you lost it.</p> <hr> <p>Now if you want something more complex using post and FormData you can easily extend this function:</p> <pre><code>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) } </code></pre> <p>Again ... it's a very short function, but it does get &amp; post.</p> <p>Examples of usage:</p> <pre><code>x(url, callback); // By default it's get so no need to set x(url, callback, 'post', {'key': 'val'}); // No need to set post data </code></pre> <p>Or pass a full form element (<code>document.getElementsByTagName('form')[0]</code>):</p> <pre><code>var fd = new FormData(form); x(url, callback, 'post', fd); </code></pre> <p>Or set some custom values:</p> <pre><code>var fd = new FormData(); fd.append('key', 'val') x(url, callback, 'post', fd); </code></pre> <p>As you can see I didn't implement sync... it's a bad thing.</p> <p>Having said that ... why don't do it the easy way?</p> <hr> <p>As mentioned in the comment the use of error &amp;&amp; synchronous does completely break the point of the answer. Which is a nice short way to use Ajax in the proper way?</p> <p><em>Error handler</em></p> <pre><code>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); </code></pre> <p>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.</p> <p>But to really get out an error the <strong>only</strong> way is to write a wrong URL in which case every browser throws an error.</p> <p>Error handlers are maybe useful if you set custom headers, set the responseType to blob array buffer or whatever....</p> <p>Even if you pass 'POSTAPAPAP' as the method it won't throw an error.</p> <p>Even if you pass 'fdggdgilfdghfldj' as formdata it won't throw an error.</p> <p>In the first case the error is inside the <code>displayAjax()</code> under <code>this.statusText</code> as <code>Method not Allowed</code>.</p> <p>In the second case, it simply works. You have to check at the server side if you passed the right post data.</p> <p>cross-domain not allowed throws error automatically.</p> <p>In the error response, there are no error codes.</p> <p>There is only the <code>this.type</code> which is set to error.</p> <p>Why add an error handler if you totally have no control over errors? Most of the errors are returned inside this in the callback function <code>displayAjax()</code>.</p> <p>So: No need for error checks if you're able to copy and paste the URL properly. ;)</p> <p><em>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</em>. I LOL'd</p> <hr> <p><em>Read a file synchronous</em></p> <p><strong>Don't do that.</strong></p> <p>If you want to block the browser for a while load a nice big txt file synchronous.</p> <pre><code>function omg(a, c){ // URL c = new XMLHttpRequest; c.open('GET', a, true); c.send(); return c; // Or c.response } </code></pre> <p>Now you can do</p> <pre><code> var res = omg('thisIsGonnaBlockThePage.txt'); </code></pre> <p>There is no other way to do this in a non-asynchronous way. (Yeah, with setTimeout loop... but seriously?)</p> <p>Another point is... if you work with APIs or just you own list's files or whatever you always use different functions for each request...</p> <p>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.</p> <hr> <p>The functions above are for basic use.</p> <p>If you want to EXTEND the function...</p> <p>Yes, you can.</p> <p>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...</p> <p>But you can do a lot of stuff with XMLHttpRequest 2:</p> <p>I made a download manager (using ranges on both sides with resume, filereader, filesystem), various image resizers converters using canvas, populate websql 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...</p> <p>But the question here is how to return an Ajax response... (I added an easy way.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload