how to set dynamic data in var a

I want to get dynamic data in one <div id = "view"> </div>

I use ajax to take dynamic data from api and insert it with var a. I will try to describe with code what I want to get exactly

$.ajax({
     url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
     method: 'get',
     dataType: "json",
     success: function (data) {
       data.forEach(function(elem){

              var a = "ID: " elem.id +"<b>" + elem.name"</b> ";
            
       })
       $('#view').html(a);
    }
});

Answer

Here you are getting the result in a foreach loop which means “a” contains all the results returned by the ajax call, in order to show only one result in a single div we would need to put the value of each loop call in the div, one way is to append the div for each result inside a parent div. I have modified your code below hopefully it helps.

HTML:

<div id = "dataholder"> </div>

JS:

$.ajax({
     url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
     method: 'get',
     dataType: "json",
     success: function (data) {
       var j = 1;
       data.forEach(function(elem){
             var a = "ID: " elem.id +"<b>" + elem.name"</b> "; 
             var view_div_id = "view-"+j;   

              $( "#inner" ).append( "<div id ="+ view_div_id +"> </div>" );
             $('#view-'+j).html(a);
              j++;

       })
      
    }
});