Jump to content

AJAX


Allerious
 Share

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>

 

Link to comment
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.

Link to comment
Share on other sites

  • 4 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...