Skip to content Skip to sidebar Skip to footer

How To Continuously Populate HTML Textbox From Curl API

I have a HTML textbox which I would like to populate with data received from an API call using curl command. The curl API that I'm using, continuously returns/livestreams data in t

Solution 1:

You can just update the value by making a GET request, and make the function repeat itself at some specified interval. Also onclick on button already adds an event listener, thus the code would go something like this.

<html>
<body>
<textarea rows='14' id="value" placeholder="anything you want here"></textarea>
<button class="get_values" onclick="startUpdate(event)">GET</button>

<script>
// to set an update interval at every 2 sec(2000ms)
function startUpdate(e) {
  // e. preventDefault();
  // calling instantly
  updateTextArea();
  // and setting interval
  window.setInterval(updateTextArea, 2000);
}

// defining global variable, to display dynamic update
window.counter = 1

function updateTextArea() {
  let url = "https://jsonplaceholder.typicode.com/todos/" + window.counter; // test url
  // assuming data is json, if it is text use response.text()
  fetch(url)
    .then(response => response.json())
    .then(data => {
      let textArea = document.getElementById("value");
      // parsing the JSON value to string
      textArea.value = JSON.stringify(data);
    })
  window.counter = window.counter + 1; // increment counter
}
</script>
</body>
</html>

Edit: To pass event you should pass the keyword event in onclick function call.


Post a Comment for "How To Continuously Populate HTML Textbox From Curl API"