I’m trying to create a JavaScript object based on a template I received as a test. I use Ajax to get the data from my database but i cant seem to create the object.
JavaScript
x
23
23
1
$(document).ready(function() {
2
$.ajax({
3
type: 'POST',
4
url: 'fetch.php',
5
dataType: 'JSON',
6
success: function(response) {
7
var test = JSON.parse(response);
8
var products = {};
9
for (var x = 0; x < test.length; x++) {
10
products[x] = {
11
productName: test[x]['name']
12
};
13
products[x] = {
14
category: test[x]['category']
15
};
16
products[x] = {
17
price: test[x]['price']
18
};
19
}
20
}
21
});
22
});
23
I’m trying to create something like this object below
JavaScript
1
20
20
1
products = {data: [
2
{
3
productName: "test_item_1",
4
category: "category1",
5
price: "49",
6
image: "test_image.jpg",
7
},
8
{
9
productName: "test_item_2",
10
category: "category3",
11
price: "99",
12
image: "test_image.jpg",
13
},
14
{
15
productName: "test_item_3",
16
category: "category3",
17
price: "29",
18
image: "test_image.jpg",
19
},],};
20
This is the how i fetch the data from my database
JavaScript
1
2
1
while($row = mysqli_fetch_assoc($run)){$datas[] = $row;}echo json_encode($datas);
2
Advertisement
Answer
Your lines with products[x]
overwrite the earlier.
Change to
JavaScript
1
6
1
products[x] = {
2
productName: test[x]['name'],
3
category: test[x]['category'],
4
price: test[x]['price'],
5
};
6