0

How to populate the select list with the values that I got with javascript?

I am sending a GET request to a .php site which gives me the respond in JSON format. Now I want to put those lines I got into the select list.

<select id = "list" name=log size=50 style=width:1028px>

<script type="text/javascript">
window.onload = function () {

  var bytes=0;
  var url = "/test/log.php?q='0'";
  function httpGet(url)
  {
    var xhttp = new XMLHttpRequest();
    var realurl = url + bytes;
    xhttp.open("GET", url, true);
    xhttp.onload = function (e) {
        if (xhttp.readyState === 4) {
            if (xhttp.status === 200) {
                console.log(xhttp.responseText);
                var response=JSON.parse(xhttp.responseText);
                var log = response.key;
                bytes = log.length;
            }
        };
    xhttp.onerror = function (e) {
        console.error(xhttp.statusText);
      }
    };


    xhttp.send();
  }

  var updateInterval = 2000; 
  function update() {

    httpGet(url);
      setTimeout(update, updateInterval);
  }

  update();
}
</script>
</select>

The response I get from log.php is "{"key":"whole log file"}". Now I want to store that reponse into a list and populate it every 2 seconds.

2
  • how do you wish to achieve that ? using Php or Javascript? Commented Jul 4, 2016 at 15:57
  • Using javascript. I want the list being populated without refreshing the page. Commented Jul 4, 2016 at 16:05

1 Answer 1

1

Loop over the contents of the returned string after JSON.parse-ing it. Create option elements from it, and insert those into the select.

 var html = "";
 var obj = JSON.parse(xhttp.responseText);
 for(var key in obj) {
   html += "<option value=" + key  + ">" +obj[key] + "</option>";
 }
 document.getElementById("list").innerHTML = html;

See JSBin

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.