Answer the question
In order to leave comments, you need to log in
How to display data from json file by specific key in javascript?
It is necessary to display the order history of one user using ajax request.
The data is requested from the php file, where it gives out a json file with information about orders.
Orders are stored in the database like this:
order_id user_id prod_name prod_qty prod_price total
10 1 Product1 2 100 200
10 1 Product2 3 50 150
11 1 Product3 1 100 100
11 1 Product4 4 50 200
$('document').ready(function(){
lengthofp = function(obj) {
var size = 0;
$.each(my_orders, function(i, elem) {
size++;
});
return size;
};
$.ajax({
type: "POST",
url: "http://sait/history.php",
data: "user_id="+localStorage.getItem("user_id"),
success: function(msg){
console.log(msg);
my_orders = JSON.parse(msg);
for(i =1;i <= lengthofp(my_orders); i++){
$(".my_history").append("<li>" +
"<div class='collapsible-header'>" +
"<div class='order-no'>" +
"<span class='block bold'>"+"Заказ №"+my_orders[i.toString()]["order_id"]+"</span>" +
"</div>" +
"</div>" +
"</li>");
}
},
error: function(){
swal("Ошибка!","Проверьте Интернет-соединение и повторите попытку","error");
}
});
});
<?php
error_reporting(E_ALL);
session_start();
define("DBHOST", "localhost");
define("DBUSER", "root");
define("DBPASS", "");
define("DB", "название");
$connection = mysqli_connect(DBHOST, DBUSER, DBPASS, DB) or die("Нет соединения с БД");
mysqli_set_charset($connection, "utf8") or die("Не установлена кодировка соединения");
if (isset($_POST['user_id'])){
$user_id = $_POST['user_id'];
global $connection;
$query = "SELECT order_id, prod_name, prod_qty, prod_price, total, delivery_date FROM orders WHERE user_id = '$user_id'";
$res = mysqli_query($connection, $query);
$i=1;
$orders = array();
while($row = mysqli_fetch_assoc($res)){
$orders[$i]= $row;
$i++;
}
echo json_encode($orders);
}
?>
Answer the question
In order to leave comments, you need to log in
Since I do not know what should be the result, there are three options.
Or we group the sample at once:
$query = "
SELECT
order_id,
SUM(total) as total
FROM orders
WHERE user_id = '$user_id'
GROUP BY order_id
;"
$orders = [];
while($row = mysqli_fetch_assoc($res)) {
$orderId = $row['order_id'];
unset($row['order_id']);
$orders[$orderId]['id'] = $orderId;
$orders[$orderId]['products'][] = $row;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question