I can not display the array data

1

When I type the command console.log (response) it displays all information in the browser console, but for some detail, I am not able to display the data inside my div that is in the html snippet below. Can anyone point out to me what I'm letting through?

<script>
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);
      }
    };

    xmlhttp.open("GET", url, true);
    xmlhttp.send();

    myFunction(url);
    function myFunction(response) {
        var arr = JSON.parse(JSON.stringify(response));
        var i;
        var out = "<div>";

        for(i = 0; i < arr.length; i++) {
            out += "<a href='#' class='samba-playlist-trigger list-group-item active' data-mediaid=" + arr[i].id + "></a>";
        }
        out += "</div>";
        document.getElementById("id01").innerHTML = out;
    }
</script>

The display part on the html page

<div class="container">
    <div class="row">
        <div id="id01"></div>
    </div>
</div>
    
asked by anonymous 17.02.2017 / 21:05

1 answer

2

Three things that come to mind:

  • What's the idea of myFunction(url); ? this line does not make sense since myFunction is what you want to use to process the right ajax result?
  • missing code that instantiates ajax
  • JSON.stringify does not make sense because you are receiving a string.

Suggestion:

function chamarAjax(url, callback) {
  var request = new XMLHttpRequest();
  request.open('GET', url, true);

  request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
      callback(request.responseText);
    } else {
      console.log('Houve um erro!');
    }
  };

  request.onerror = function() {
    console.log('Houve um erro!');
  };

  request.send();
}

function myFunction(response) {
  var arr = JSON.parse(response);
  var ancoras = arr.map(function(obj) {
    return "<a href='#' class='samba-playlist-trigger list-group-item active' data-mediaid='" + obj.id + "'>Link</a>";
  }).join('');
  document.getElementById("id01").innerHTML = ["<div>", ancoras, "</div>"].join('');
}

chamarAjax('http://sergiofrilans.se/so_pt_stuff/184974.php', myFunction);
a {
  display: block;
}
<div id="id01"></div>

This way you have ajax within a function and your function to process the ajax to be passed as a callback, getting everything organized.

    
17.02.2017 / 21:17