Y
Y
Yura_Mart2018-12-26 00:08:03
PHP
Yura_Mart, 2018-12-26 00:08:03

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


Here is the js code:
$('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");
        }
    });
});


And php:
<?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);
}

?>


Orders are displayed in this way:

Order No. 10
Order No. 10
Order No. 11
Order No. 11 And you need to do it by

order_id:

Order No. 10
Order No. 11

in the future, you will need to display all the products in each order, but you need to display it in javascript by a specific key.
Can you please tell me how to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Marat Garifullin, 2018-12-26
@Yura_Mart

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
;"

Or we group on the server 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;
}

Or do the same on the client...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question