0

I'm making an XMLHttpRequest to upload an image file. I can see that it's a 200 status and my image is uploading onto my service. However, when I use the code below to get the responseText (which should include information such as: URL for my image, filename, timestamps, image dimensions, etc.), it comes back as an empty string:

  //...

  const data = new FormData();
  data.append('file', props);
  data.append('upload_preset', uploadPreset);
  data.append('api_key', apiKey);

  const xhr = new XMLHttpRequest();
  xhr.open('POST', cloudinaryURL, true);
  const sendImage = xhr.send(data);
  const imageResponse = xhr.responseText;
  console.log('Response: ', imageResponse);

Prints this to the console:

Response:  

Any idea why this is happening / how to resolve this issue?

Thanks!!

dace
  • 5,819
  • 13
  • 44
  • 74

1 Answers1

4

You are using XMLHttpRequest in asynchronous mode:

xhr.open('POST', cloudinaryURL, true);

But your code is designed for synchronous mode:

xhr.open('POST', cloudinaryURL, false);

In asynchronous mode, xhr.send() will return immediately without actually processing the request. So, xhr.responseText hasn't been populated yet when you try to access it.

Arnauld
  • 5,847
  • 2
  • 15
  • 32
  • Yes, this solved my issue! Thanks so much for pointing out the problem and explaining. Appreciate it. – dace Jul 22 '16 at 14:43
  • 1
    I'm glad it helped. As a side note, I would in fact recommend to use asynchronous mode to avoid browser unresponsiveness. You can see a live example [here](http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first). – Arnauld Jul 22 '16 at 15:14
  • Great, thanks for the example. So it looks like I can run this asynchronously and get access to responseText if readyState == 4 and status == 200. Very good to know. Thank you!! – dace Jul 22 '16 at 15:19