1

I am using jQuery and JSON to get data from database

$("#openNotification").on('click', function(e)
{
    ID = "a";
    $.ajax(
    {
        url: "notificationDetail",
        type: "POST",
        data:
        {
            designationID: ID
        },
        dataType: "JSON",
        success: function (jsonStr)
        {
            $(".processingNotification").hide();

            var jSonLength = jsonStr.length;

            for (var i=0; i<jSonLength; i++)
            {
                var userAvatar = jsonStr[0].userAvatar;

                var newrow = "<div class='subNotification'><img src='assets/img/avatar/"+userAvatar+"'/></div>";


            }


            $(".opened_page").html(newrow);
        }
    });
});

HTML

<div class="opened_page"></div>

When I click #openNotification I can see the jSon data from PHP

enter image description here

But when I want to display the data to .opened_page it only show 1 data.

2 Answers 2

3

you are replacing with new value, code should be

var newrow = '';
for (var i=0; i<jSonLength; i++)
{
     var userAvatar = jsonStr[0].userAvatar;
     newrow += "<div class='subNotification'><img src='assets/img/avatar/"+userAvatar+"'/></div>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can also use jQuery append() function here.

For eg.

for(var i = 0; i < jSonLength; i++){
   var userAvatar = jsonStr[i].userAvatar;
   $(".opened_page").append("<div class='subNotification'><img src='assets/img/avatar/"+userAvatar+"'/></div>");
}

So your final code would be like,

$("#openNotification").on('click', function(e){
    ID = "a";
    $.ajax({
        url: "notificationDetail",
        type: "POST",
        data: {
            designationID: ID
        },
        dataType: "JSON",
        success: function (jsonStr){
            $(".processingNotification").hide();
            var jSonLength = jsonStr.length;

            for(var i = 0; i < jSonLength; i++){
                var userAvatar = jsonStr[i].userAvatar;
                $(".opened_page").append("<div class='subNotification'><img src='assets/img/avatar/"+userAvatar+"'/></div>");
            }
        }
    });
});

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.