0

I have json data in this structure

here is my json code https://jsonblob.com/309e8861-7f26-11e7-9e0d-cf3972f3635e

and here is my jquery code example

$("#getJsonData").click(function(){
    $.get(base_url + 'roles/index', function(data) {
        var data = $.parseJSON(data);
        $.each(data, function(index, val) {
            $("#result").html("<p>" + val.name + "</p>");
        });
    });
});

HTML file

<button id="getJsonData">Load role list</button>

    <div id="result"></div>

I don't get this, I get every value from json in console when do console.log, but when use html method to display result as html in screen it just showing last value from ending last json array. What is wrong here?

3 Answers 3

2

jquery .html always overrite previous html so we cant use html in loop section instead of that we can use append it simply append your p tag in result div Instead of using this:-

$("#result").html("<p>" + val.name + "</p>");

use like this:-

$("#result").append("<p>" + val.name + "</p>");
Sign up to request clarification or add additional context in comments.

2 Comments

But it will append same data result over and over clicking the button, is it right way even?
can you post your present output in screenshot?
0

You are overwriting the html with the code

$("#result").html("<p>" + val.name + "</p>");

Instead you can store the result in variable and then you write it to the element.Like this

$("#getJsonData").click(function(){
  $.get(base_url + 'roles/index', function(data) {
    var data = $.parseJSON(data);
    var html = '';
    $.each(data, function(index, val) {
        html +="<p>" + val.name + "</p>";
    });        
    $("#result").html(html);
  });
});

Comments

0

Your code should be :

$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
    var data = $.parseJSON(data);
    var listHtml="";
    $.each(data, function(index, val) {
       listHtml=listHtml+ "<p>" + val.name + "</p>";
    });
   $("#result").html(listHtml);
});

});

And Html should be same as your

<button id="getJsonData">Load role list</button>

<div id="result"></div>

Working example is here

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.