Skip to main content
1 of 4

Improvement suggestions for first AJAX application

Today I created my first simple AJAX application. It works fine, but I am a bit unsure if I did everything correct.

My code looks like this:

function _solve(id) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { var DONE = 4; // readyState 4 means the request is done. var OK = 200; // status 200 is a successful return. if (xhr.readyState === DONE) { if (xhr.status === OK) { obj = JSON.parse(xhr.responseText); if (obj.success) { if (document.getElementById('line'+obj.id).style.display != 'none') { document.getElementById('line'+obj.id).style.display = 'none'; document.getElementById('count').innerHTML = document.getElementById('count').innerHTML - 1; } } else { alert('Json error: ' + obj.error); } } else { alert('Error: ' + xhr.status); // An error occurred during the request. } } }; xhr.open('POST', 'ajax_cmd.php', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send('cmd=solve&id='+id); } 

Beside general improvement suggestions, I have following particular questions:

  1. Do I need to somehow close the connection? It looks like send() automatically closes the connection because I cannot execute send() twice.

  2. Is the error handling ok? When my internet connection was a bit unstable, I got the message "Error: 0". Zero sounds like a strange status code.

Note: For now, I'd like to stick with plain JavaScript, without jQuery or other frameworks.

Thank you very much.