Unable to display Json Response in input checkbox tag

1.4k views Asked by At

I am trying to display Json Response in input checkbox tag on button click. But i am unable to do it.

Can anyone guide me how to do it.

Below is the code -

   <!DOCTYPE html>
<html>
<body>
<script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>

<label><input type="checkbox" name="test_name" value=""></label>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementsByName('test_name').innerHTML = JSON.stringify(this.responseText,undefined, 2).replace(/\\n/g, "").replace(/\\r/g, "")
                                                                                      .replace(/\\/g, "")
                                                                                      .replace(/^"/, "")
                                                                                      .replace(/"$/, "");
    var jsonobj =  JSON.parse(document.getElementsByName('test_name').innerHTML);

    for ( var i=0;i<jsonobj.length; i++) 
    {
         console.log(jsonobj[i].Newsletter_Name);

             var label = document.getElementsByName('test_name'); 
             console.log(label);
             label.value= jsonobj[i].Newsletter_Name;               
    }; 

    }
  };
  xhttp.open("GET", "https://members.s7.exacttarget.com/Pages/Page.aspx?QS=38dfbe491fab00ea764e20685ddf905a854eb2c63c649afb00651f16b30a4189&brand_code=PE", true);
  xhttp.send();

}

</script>

</body>
</html>

Json Return - There will be a lot of data. But i am displaying few.

[{
"Test_Name": "FOOD",
"Brand": "Test"
},
{
"Test_Name": "HOME",
"Brand": "Test"
}]
2

There are 2 answers

1
Teknotica On

Sticking with jQuery only (read more here) - to tick the checkboxes from the values in your JSON, you can do something like this:

$.ajax({
    url: "https://testendpoint/",
    dataType: "json",
    success: function (response) {
        if (response) {
            // Tick checkboxes from JSON
            for (var i=0; i<json.length; i++) {
                $('#' + json[i].Newsletter_Name).prop('checked', true);
            }
        }
    }
});

That is assuming your checkboxes look something like this:

<div>
    <input id="FOOD" type="checkbox" value="FOOD">
    <label for="Food">Food</label>          

    <input id="HOME" type="checkbox" value="HOME">
    <label for="Home">Home</label>
</div>
0
Silas On

I can't access the URL you are using, so I'll give an example using Librivox.org API:

A couple of points:

1: You don't need to populate a DOM innerText first - the returned value is available already.

2: Unless you have a good reason (performance usually) you should use JQuery as others have said because it hides x-browser issues when using native XMLHTTPRequest.

3: I think you are trying to render a checkbox per item returned. This is what I will show.

The proxy used is simply a C# handler to pass the request to the remote server, so I don't run into cross-domain request issues. The response is exactly as returned directly from the following call:

https://librivox.org/api/feed/authors?format=json

JQuery will automatically convert the returned JSON string into a Javascript object - which you can see with the console.log() statement.

The code makes a request to the remote server (Librivox) and returns a list of data (authors) as a JSON string. Because I passed the type 'json' as the expected return type, JQuery will automatically convert the data into a usable Javascript object.

The rest of the code just builds up a collection of checkboxes, and appends to a specified DOM element.

It would be straightforward to attach click handlers to each checkbox to further process the data.

<!DOCTYPE html>
<html>
<body>
    <script src="js/libs/jquery/jquery.js" type="text/javascript"></script>

<label><input type="checkbox" name="test_name" value=""></label>

<div id="test"><!-- Appending checkboxes here -->

</div>

<button type="button" id="loaddoc">Change Content</button>

<script>
var proxyUrl = "/proxy/proxy.aspx";

$(function(){
        $.ajax(proxyUrl + "?endpoint=api/feed/authors",{
            dataType:"json"
        }).complete(function(data){ 
            //log data:
            console.log(data);//big list of authors
            var dv = document.createElement("div");
            //build checkboxes...
            for(var a=0;a<data.responseJSON.authors.length;a++){
                var lbl = document.createElement("label");
                lbl.appendChild(document.createTextNode(data.responseJSON.authors[a].last_name));
                var chk = document.createElement("input");
                chk.setAttribute("type","checkbox");
                chk.setAttribute("name",data.responseJSON.authors[a].last_name);
                chk.setAttribute("value",data.responseJSON.authors[a].id);
                lbl.appendChild(chk);
                dv.appendChild(lbl);
            }
            //append to element:
            $("#test")[0].appendChild(dv);
        });
});
</script>
</body>
</html>