Forum Moderators: open

Message Too Old, No Replies

Question on create simple call

         

soupi

3:31 pm on Aug 12, 2020 (gmt 0)

5+ Year Member



Whats the best way to put together a simple webpage that contains a javascript code that calls an ajax function to retrieve some data and finally display that data in the simple webpage.

currently I only have
<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h2>AJAX Text</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>

</body>
</html>

NickMNS

3:48 pm on Aug 12, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The best way is using js Fetch API. See the link below:
[developer.mozilla.org...]

soupi

3:55 pm on Aug 12, 2020 (gmt 0)

5+ Year Member



Ty, where do I put the sample data i am trying to retrieve like "This is a test call"

NickMNS

4:18 pm on Aug 12, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You need to create an endpoint on your server, in other words a url, like example.com/test-call-data. Then client side (on the webpage) using fetch, you fetch('/test-call-data'). That will make a request to the server, and your server should respond by returning the data, typically (but not always) in a JSON format.

How you do this on server depends on what software you are using (PHP / Python / NodeJS).

soupi

3:37 pm on Aug 14, 2020 (gmt 0)

5+ Year Member



Last question, How would I add error handling to this?
<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h2>AJAX Task</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "text.txt", true);
xhttp.send();
}
</script>

</body>
</html>

NickMNS

7:34 pm on Aug 14, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You are complicating you life by not using the Fetch API.
Here is a developers.google.com post answering your exact question, and providing both methods. You will see from the post that the Fetch way is much simpler.
[developers.google.com...]