Jump to content

Recommended Posts

The code i've supplied is from this link:

https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_first

The only difference being that i've removed the 'xhttp.onreadystatechange' function creation.

Does 'responseText' in my code not output anything because at the point that piece of code is run the response hasn't been received from the server yet? I'm thinking maybe there's a slight delay hence the need for the piece of code i removed i.e the removed code is needed as it's only run once the response is received from the server i.e when the 'readyState' and 'status' changes. I assume that is why my code doesn't run with that piece of code removed but wanted to be sure.

<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<p id="demo">Let AJAX change this text.</p>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
loadDoc(){
  var xhttp = new XMLHttpRequest();

  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
  
  document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>

</body>
</html>

 

Share this post


Link to post
Share on other sites

You have to add an onreadystatechange event listener. Check the AJAX examples in the tutorials.

That is the event which fires once the server has given a response.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...