3

I want to retrieve the data contained in a text file (from a given URL) through JavaScript (running on the client's browser).

So far, I've tried the following approach:

var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;

But it only works for Firefox. Does anyone have any suggestions to make this work in every browser?

Thanks

federico-t
  • 12,014
  • 19
  • 67
  • 111

2 Answers2

3

IT works using xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); in IE older versions. Chrome, Firefox and all sensible browsers use xhr

Frankly, if you want cross browser compatibility, use jquery

its pretty simple there:

var text="";
$.get(url, function(data){text=data;//Do something more with the data here. data variable contains the response})
SoWhat
  • 5,564
  • 2
  • 28
  • 59
  • Thanks for the jQuery tip, it really makes things easier. Thing is, now Chrome is throwing the following error: `XMLHttpRequest cannot load http://example.com/file.txt. Origin null is not allowed by Access-Control-Allow-Origin.`. Do you have any idea of why this might be happening? – federico-t Feb 06 '12 at 05:48
  • that's cuz u can only access a file on the same host as the page. For example if you use this in http://example1.com/page.php You can only access files on http://example1.com, not anywhere else on the internet. Thus http://example.com will be blocked. I suppose you're using this on localhost. To give a more concrete idea, if the page is on http://facebook.com, you can only access http://facebook.com /* not http://twitter.com Its a security restriction imposed by most browsers – SoWhat Feb 06 '12 at 06:01
  • @JohnDoe Read up on *Cross-Origin Request Sharing*. – Gumbo Feb 06 '12 at 09:42
  • Thanks to both, although I prefer the jQuery approach (so that I don't have to make a custom solution for each browser) – federico-t Feb 06 '12 at 10:15
-1
var xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadFile'); 
var form = new FormData();
form.append('file', fileInput.files[0]);
xhr.send(form);

It was previously impossible to upload binary data with XMLHttpRequest object, because it could not stand the use of FormData (which, anyway, did not exist at that time) object. However, since the arrival of the new object and the second version of XMLHttpRequest, this "feat" is now easily achievable

It's very simple, we just spent our File object to a FormData object and upload it

  • 4
    Can you provide some explanation to your answer, since just code, with French comment (change it to English), could be seen as an incomplete answer. – Jonathan Drapeau Jul 17 '14 at 15:09
  • I don't think this even answers the question. The question was about retrieving a file, this code sends a file. – jmoerdyk Jul 17 '14 at 15:12