so I want to load multiple cards into 1 div box, some with same css classes, some different, so I create one array of objects to load these different classes into them. In the mean time, I have other array of object including data to load too.
What I'm trying here is loops these 2 arrays in 1 for loop statement (same length by using same iterator) but one of them returned with undefined, can someone help me please, what am I doing wrong? (The code below is just a simple version of mine because the real one is really long)
<div id="recently-added" >
// here to load multiple cards
</div>
var DB = [];
$.get(`http://localhost:8080/real-estate/monthly`, function(res) {
DB.push(res);
})
load();
function load() {
var card = '';
var classNum = [
{ 'list': '1', 'text': '2'},
{ 'list': '2', 'text': '5'}
];
for (let index = 0; index < classNum.length; index ) {
var data = DB[index];
card =
`
<div >
<div >
<img >
<p >Click to select the text box</p>
<h4 u-text-${classNum[index].text}">${data.title}</h4>
<a >detail</a>
</div>
</div>
`
}
$("#recently-added").html(card);
}
The DB I took from ajax call and it somehome looks like this:
var DB = [
{'id': 1350, 'title': '2-room apartment with pool view', 'type': 0, 'request': 0},
{'id': 1351, 'title': 'newly built house', 'type': 0, 'request': 1}
];
As I watched them through console, the data
variable returned undefined https://imgur.com/a/6ZlWc4C
This is kind of the result I expect: https://imgur.com/a/ttkh17I
CodePudding user response:
$.get(`http://localhost:8080/real-estate/monthly`, function(res) {
load(res.data); // or however your get call returns the atual array you want
})
function load(DB) {
var card = '';
var classNum = [
{ 'list': '1', 'text': '2'},
{ 'list': '2', 'text': '5'}
];
// note that now you are checking two arrays using the length of only one array
// and you dont control the other array,
//so this will likely cause you problems if only 1 element is returned from
// the get call
for (let index = 0; index < classNum.length; index ) {
var data = DB[index];
card =
`
<div >
<div >
<img >
<p >Click to select the text box</p>
<h4 u-text-${classNum[index].text}">${data.title}</h4>
<a >detail</a>
</div>
</div>
`
}
$("#recently-added").html(card);
}
CodePudding user response:
Try this one - call load()
only after fetching results:
$.get(`http://localhost:8080/real-estate/monthly`, function(res) {
DB.push(res);
load();
})