0

So I was trying to fetch some data from my node.js server(using express.js) through jQuery.getJSON().

Here's the relevant code:

test.html:

<script>
$.getJSON('/test', function(data, status, xhr){
    document.write(data.message);
    //console.log(data.message);
});
</script>

server.js:

app.get('/test', function(req, res){
    res.json({ message: 'Hello World' });
});

Now, things work fine when just a console.log() is used but when a document.write() is issued, the request doesn't complete even though the data is fetched i.e. the browser goes into an indefinite loading state after fetching the data.

The status text sent to the callback reads 'success' so I am guessing there is no error on the ajax side setup.

I'm using jQuery 1.11.1 and node.js 0.13.0.

What could be causing this?

galactocalypse
  • 1,805
  • 1
  • 12
  • 28

1 Answers1

1

document.write() automatically calls document.open() which basically clears your current document (source: MDN), so probably the browser don't have enough time to close the XHR connection resulting in a "indefinite loading state". Calling document.close() afterwards should fix the problem.

But first of all please notice that you should never use document.write after your webpage has finished loading (which i guess is your case) and it's generally considered to be a bad practise.

Community
  • 1
  • 1
lukaszfiszer
  • 2,271
  • 17
  • 13
  • Indeed! Adding `document.close()` after the write got rid of the indefinite loading state. I was only using `document.write()` to quickly test if the data was getting transferred properly or not - and ran into the above problem in the process, so just got curious. I am using `jQuery.html()` in the actual file. Thank you! – galactocalypse Nov 25 '14 at 03:06
  • Great. I've updated my answer so it mentions clearly that calling `document.close()` solves the problem. – lukaszfiszer Nov 25 '14 at 12:46