• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Wpisywanie i wydobywanie do i z pliku json

VMware Cloud PRO - przenieś swoją infrastrukturę IT do chmury
0 głosów
766 wizyt
pytanie zadane 3 stycznia 2020 w JavaScript przez Młody programista Obywatel (1,200 p.)
edycja 3 stycznia 2020 przez Młody programista

Moim problemem jest wpisywanie danych rejestracji ( i operacji na nich np. sprawdzanie czy taki użytkownik jest zarejestrowany) do pliku .json . Tworze projekt sklepu i nie wiem jak sobie z tym poradzić. Problemem jest też koszyk, który nie działa, nie wiem jak go zrobić, tzn dodać te wszystkie parametry jak w sklepach ( dynamicznie dodawać i usuwać produkty ) i oczywiście w pliku .json. Z góry dziękuję za jakąkolwiek  pomoc w próbie napisania kodu

PS. wiem, że dużo się opisałem ;)  

Kod html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Niezwykły sklepik</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" />
    <link rel="stylesheet" href="main.css" />
</head>
<body>
    <nav class="navbar" id="log">
        <div class="navbar-center">
            <img src="img/logo.jpg" alt="store logo" />
            <div class="cart-btn">
                <span class="nav-icon">
            <i class="fas fa-cart-plus"></i>
          </span>
                <div class="cart-items">0</div>
            </div>
        </div>
        <div class="boxx" id="logi">
            <!--action="index.html" method="post" -->
            <input type="email" placeholder="Login" id="login">
            <input type="password" placeholder="Hasło" id="haslo"><br>
            <input type="button" value="Zaloguj" id="loguj">
            <a href="rejestracja.html">
                <input type="button" value="Zarejestruj"></a>
        </div>
    </nav>
    <section class="products">
        <div class="section-title">
            <h2>Produkty</h2><br>
        </div>
        <div class="products-center">
            <article class="product">
                <div class="img-container">
                    <center><img src="img/titan.jpg" alt="product" class="product-img" /></center>
                    <button class="bag-btn" data-id="1">
              <i class="fas fa-shopping-cart"></i>
              Dodaj do koszyka
            </button>
                </div>

                <h3>Titan RTX 24 GB GDDR6</h3>
                <h4>12.350 zł</h4>
            </article>
        </div><br><br>
        <!-- jeszcze pare produktów -->
    </section>
    <div class="cart-overlay">
        <div class="cart">
            <span class="close-cart"><i class="far fa-window-close"></i></span>
            <h2>Koszyk</h2>
            <div class="cart-content">
                
                <!-- <div class="cart-item">
                    <img src="imag/titan.jpeg" alt="product" />
                    <div>
                        <h4>TITAN RTX 24 GB GDDR6</h4>
                        <h5>12.350 zł</h5>
                        <span class="remove-item">Usuń</span>
                    </div>
                    <div>
                        <i class="fas fa-chevron-up"></i>
                        <p class="item-amount">
                            1
                        </p>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div> -->
                
            </div>
            <div class="cart-footer">
                <h3>Razem : <span class="cart-total">0</span> zł</h3>
                <button class="clear-cart banner-btn">Wyczyść koszyk</button>
            </div>
        </div>
    </div>

    <script src="js/app.js">
    </script>

</body>


</html>

Kod js:

var log = document.getElementById('loguj');
const logowanie = e => {
    var login = document.getElementById('login').value;
    var password = document.getElementById('haslo').value;
    var user = {
        login: login,
        password: password
    }
    console.log(user);
    var JSONuser = JSON.stringify(user);
    console.log(JSONuser);

    if ((login.length > 5) && password.length > 8) {
        document.getElementById('logi').innerHTML = '';
        document.getElementById('logi').innerHTML = login + '<br><br>'
        var menu = document.getElementById('logi');
        var backindex = document.createElement('div');
        backindex.classList.add("boxx");
        var wyloguj = document.createElement('button');
        wyloguj.classList.add("boxx");
        wyloguj.setAttribute('id', 'logout');
        wyloguj.innerHTML = 'Wyloguj się';
        menu.appendChild(wyloguj);

    } else alert('Złe dane logowania');

    wyloguj.addEventListener('click', function() {
        location.reload();
    })
var config = getJSON("db/config.json");
    console.log(config);
loguj.addEventListener('click', logowanie)

const config = {
    filepath: "db/config.json",
    name: "Niezwykły sklep",
    addres: "http://szkola.n-soft.pl/lfraczek/Sklep",
    database: {
        config: "db/config.json",
        users: "db/users.json",
        products: "db/products.json",
        orders: "db/orders.json",
    },
    interface: {
        defaultSort: "name",
            defaultItems: 12,
            defaultLang: "pl"
    }
}

Strona rejestracji:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="img/favicon.png" type="image/png">
    <title>Rejestracja</title>
    <!-- <link rel="stylesheet" href="css/styles.css">
    <link rel="stylesheet" href="css/skeleton.css"> -->

</head>
<style>
    .box {
        width: 500px;
        padding: 20px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #e0e0e0;
        text-align: center;
    }
    
    .box h1 {
        color: rgb(31, 2, 2);
        text-transform: uppercase;
        font-weight: 500;
    }
    
    .box input[type="email"],
    .box input[type="text"],
    .box input[type="date"],
    .box input[type="text"],
    .box input[type="password"] {
        border: 0;
        background: none;
        display: block;
        margin: 1px auto;
        text-align: center;
        border: 2px solid #b5dd5a;
        padding: 4px 10px;
        width: 200px;
        outline: none;
        color: rgb(0, 0, 0);
        border-radius: 24px;
        transition: 0.25s;
    }
    
    .box input[type="email"]:focus,
    .box input[type="text"]:focus,
    .box input[type="date"]:focus,
    .box input[type="password"]:focus {
        width: 280px;
        border-color: #2ecc71;
    }
    
    .box input[type="submit"],
    .box input[type="button"] {
        border: 0;
        background: none;
        display: block;
        margin: 10px auto;
        text-align: center;
        border: 2px solid #b5dd5a;
        padding: 2px 30px;
        outline: none;
        color: rgb(7, 0, 0);
        border-radius: 24px;
        transition: 0.25s;
        cursor: pointer;
    }
    
    .box input[type="submit"]:hover,
    .box input[type="button"]:hover {
        background: #2ecc71;
    }
</style>

<body>
    <div>
        <center>
            <form class="box" action="index.html" method="post">
                <h1>Rejestracja</h1>
                <input type="text" name="" placeholder="Imie"><br><br>
                <input type="text" name="" placeholder="Nazwisko"><br><br>
                <input type="text" name="" placeholder="Adres zamieszkania"><br><br>
                <input type="text" name="" placeholder="Kod pocztowy"><br><br>
                <input type="email" name="" placeholder="Email"><br><br>
                <input type="password" name="" placeholder="Hasło"><br><br>
                <input type="password" name="" placeholder="Powtórz hasło"><br><br>
                <input type="submit" value="Zarejestruj">

            </form>
        </center><br>
    </div>
</body>

</html>
komentarz 3 stycznia 2020 przez Młody programista Obywatel (1,200 p.)

CSS:

@import url("https://fonts.googleapis.com/css?family=Lato:400,700");
     :root {
        --primaryColor: #f09d51;
        --mainWhite: #fff;
        --mainBlack: #222;
        --mainGrey: #ececec;
        --mainSpacing: 0.1rem;
        --mainTransition: all 0.3s linear;
    }
    
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    body {
        color: var(--mainBlack);
        background: rgb(255, 255, 255);
        font-family: "Lato", sans-serif;
    }
    .navbar {
        background: var(--mainWhite);
        position: sticky;
        top: 0;
        height: 65px;
        width: 100%;
        display: flex;
        align-items: center;
        background: rgb(173, 136, 99);
        z-index: 1;
    }
    
    .navbar-center {
        width: 100%;
        max-width: 1170px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 1.5rem;
    }
    
    .nav-icon {
        font-size: 1.5rem;
    }
    
    .cart-btn {
        position: relative;
        cursor: pointer;
    }
    
    .cart-items {
        position: absolute;
        top: -8px;
        right: -8px;
        background: var(--primaryColor);
        padding: 0 5px;
        border-radius: 30%;
        color: var(--mainWhite);
    }
    
    .hero {
        min-height: calc(100vh - 60px);
        background: url("./images/hero-bcg.jpeg") center/cover no-repeat;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .banner {
        text-align: center;
        background: rgba(255, 255, 255, 0.8);
        display: inline-block;
        padding: 2rem;
    }
    
    .banner-title {
        font-size: 3.4rem;
        text-transform: uppercase;
        letter-spacing: var(--mainSpacing);
        margin-bottom: 3rem;
    }
    
    .banner-btn {
        padding: 1rem 3rem;
        text-transform: uppercase;
        letter-spacing: var(--mainSpacing);
        font-size: 1rem;
        background: var(--primaryColor);
        color: var(--mainBlack);
        border: 1px solid var(--primaryColor);
        transition: var(--mainTransition);
        cursor: pointer;
    }
    
    .banner-btn:hover {
        background: transparent;
        color: var(--primaryColor);
    }
    
    .cart-overlay {
        position: fixed;
        top: 0;
        right: 0;
        width: 100%;
        height: 100%;
        transition: var(--mainTransition);
        background: rgb(240, 157, 81, 0.5);
        z-index: 2;
        visibility: hidden;
    }
    
    .cart {
        position: fixed;
        top: 0;
        right: 0;
        width: 100%;
        height: 100%;
        overflow: scroll;
        background: var(--mainWhite);
        z-index: 3;
        background: rgb(231, 226, 221);
        padding: 1.5rem;
        transition: var(--mainTransition);
        transform: translateX(100%);
    }
    
    .showCart {
        transform: translateX(0);
    }
    
    .transparentBcg {
        visibility: visible;
    }
    
    @media screen and (min-width: 768px) {
        .cart {
            width: 30vw;
            min-width: 450px;
        }
    }
    
    .close-cart {
        font-size: 1.7rem;
        cursor: pointer;
    }
    
    .cart h2 {
        text-transform: capitalize;
        text-align: center;
        letter-spacing: var(--mainSpacing);
        margin-bottom: 2rem;
    }
    
    .cart-item {
        display: grid;
        align-items: center;
        grid-template-columns: auto 1fr auto;
        grid-column-gap: 1.5rem;
        margin: 1.5rem 0;
    }
    
    .cart-item img {
        width: 75px;
        height: 75px;
    }
    
    .cart-item h4 {
        font-size: 0.85rem;
        text-transform: capitalize;
        letter-spacing: var(--mainSpacing);
    }
    
    .cart-item h5 {
        margin: 0.5rem 0;
        letter-spacing: var(--mainSpacing);
    }
    
    .item-amount {
        text-align: center;
    }
    
    .remove-item {
        color: grey;
        cursor: pointer;
    }
    
    .fa-chevron-up,
    .fa-chevron-down {
        color: var(--primaryColor);
        cursor: pointer;
    }

    
    .cart-footer {
        margin-top: 2rem;
        letter-spacing: var(--mainSpacing);
        text-align: center;
    }
    
    .cart-footer h3 {
        text-transform: capitalize;
        margin-bottom: 1rem;
    }

    
    .products {
        padding: 4rem 0;
    }
    
    .section-title h2 {
        text-align: center;
        font-size: 2.5rem;
        /* margin-bottom: 5rem; */
        text-transform: capitalize;
        letter-spacing: var(--mainSpacing);
    }
    
    .products-center {
        /* width: 90vw; */
        margin: 0 auto;
        max-width: 800px;
        /* display: grid; */
        /* grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
    grid-column-gap: 1.5rem;
    grid-row-gap: 2rem; */
    }
    
    .img-container {
        position: relative;
        overflow: hidden;
    }
    
    .bag-btn {
        position: absolute;
        top: 70%;
        right: 0;
        background: var(--primaryColor);
        border: none;
        text-transform: uppercase;
        padding: 0.5rem 0.75rem;
        letter-spacing: var(--mainSpacing);
        font-weight: bold;
        transition: var(--mainTransition);
        transform: translateX(101%);
        cursor: pointer;
    }
    
    .bag-btn:hover {
        color: var(--mainWhite);
    }
    
    .fa-shopping-cart {
        margin-right: 0.5rem;
    }
    
    .img-container:hover .bag-btn {
        transform: translateX(0);
    }
    
    .product-img {
        width: 30%;
        /* min-height: 12rem;
    transition: var(--mainTransition); */
    }
    
    .img-container:hover .product-img {
        opacity: 0.5;
    }
    
    .product h3 {
        text-transform: capitalize;
        font-size: 1.1rem;
        margin-top: 1rem;
        letter-spacing: var(--mainSpacing);
        text-align: center;
    }
    
    .product h4 {
        margin-top: 0.7rem;
        letter-spacing: var(--mainSpacing);
        color: purple;
        text-align: center;
    }   
    .boxx {
        text-align: center;
    }
    
    .box h1 {
        color: white;
        text-transform: uppercase;
        font-weight: 500;
    }
    
    .boxx input[type="email"],
    .boxx input[type="password"] {
        border: 0;
        background: lightcyan;
        text-align: center;
        border: 2px solid #3498db;
        width: 200px;
        outline: none;
        color: rgb(0, 0, 0);
        border-radius: 10px;
    }
    
    .boxx input[type="email"]:focus,
    .boxx input[type="password"]:focus {
        width: 300px;
        border-color: #2ecc71;
    }
    
    .boxx input[type="submit"],
    .boxx input[type="button"] {
        border: 0;
        background: lightcyan;
        text-align: center;
        border: 2px solid #2ecc71;
        outline: none;
        color: rgb(73, 6, 6);
        border-radius: 15px;
        cursor: pointer;
        width: 100px;
    }
    
    .boxx input[type="submit"]:hover,
    .boxx input[type="button"]:hover {
        background: #2ecc71;
    }

 

1 odpowiedź

0 głosów
odpowiedź 3 stycznia 2020 przez smokolisz Mądrala (6,340 p.)
Wszystkie dane np klientów (login, hasło, adres), produktów (id, nazwa, opis, cena) przechowuj w bazie danych.

Koszyk możesz zrobić jako tabelę z polami np id, idUzytkownika, idProduktu, ilosc. Kiedy użytkownik dodaje produkt do koszyka wstawiasz rekord do bazy. Na podstronie z koszykiem pobierasz znowu te dane i wyświetlasz w tabelce.

Jeżeli nie wiesz jak tworzyć bazy danych zainteresuj się jakimś poradnikiem. Będziesz musiał napisać troche kodu w php i kwerendy w sql
komentarz 4 stycznia 2020 przez Młody programista Obywatel (1,200 p.)
function saveJSON(jsonObject, filePath, append = false) {
        const xhr = new XMLHttpRequest();

        xhr.addEventListener("load", function() {
            if (xhr.status !== 200) {
                console.log("Błąd komunikacji z php");
            }
        });

        xhr.open("POST", encodeURI("saveJSON.php?append=" + append + "&filepath=" + filePath), true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.send(JSON.stringify(jsonObject));
    }

    function getJSON(filePath) {
        const xhr = new XMLHttpRequest();

        xhr.open("GET", filePath, false);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.send();

        if (xhr.status !== 200) {
            return null;
        } else {
            return JSON.parse(xhr.response);
        }
    }

Nie wiem, czy o to chodzi, ale to pliczek saveJSON.php

<?php

if ($_GET['append'] == 'true') {

    $data = json_decode(file_get_contents($_GET['filepath']));

    if( !is_array($data) )
        $json[] = $data;
    else
        $json = $data;

    $json[] = json_decode( file_get_contents("php://input") );
    
    file_put_contents($_GET['filepath'], json_encode($json) );
}
else
    file_put_contents($_GET['filepath'], file_get_contents("php://input"));

if (!file_exists($_GET['filepath']))
    echo 'Blad zapisu pliku';
else
    echo 'OK';
?>

Tego zapisywania nie wiem

1
komentarz 4 stycznia 2020 przez Tomek Sochacki Ekspert (227,490 p.)

@smokolisz,

Koszyk możesz zrobić jako tabelę z polami np id, idUzytkownika, idProduktu, ilosc. Kiedy użytkownik dodaje produkt do koszyka wstawiasz rekord do bazy. Na podstronie z koszykiem pobierasz znowu te dane i wyświetlasz w tabelce.

koszyk to nie taka prosta sprawa... jest to moment, gdy user jeszcze nie kupił tych produktow a jedynie dodal je do koszyka... każde wyświetlenie powinno więc też sprawdzać np. czy produkt jest jeszcze w ogóle dostępny, jeśli user dostał na niego jakiś rabat to test czy nadal ten rabat obowiązuje itp. itd. Jest tu naprawdę masa różnych warunków i zależności... to nie tylko proste zapisanie do jednej tabelki i odczytywanie :)

Podobne pytania

+1 głos
2 odpowiedzi 2,237 wizyt
pytanie zadane 8 września 2020 w JavaScript przez Marak123 Stary wyjadacz (11,190 p.)
0 głosów
0 odpowiedzi 710 wizyt
pytanie zadane 11 lutego 2020 w JavaScript przez Młody programista Obywatel (1,200 p.)
0 głosów
1 odpowiedź 765 wizyt

93,440 zapytań

142,431 odpowiedzi

322,678 komentarzy

62,802 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj

...