0
// LocalStorage is a lowdb adapter for saving to localStorage
const adapter = new LocalStorage('db')

// Create database instance
const db = low(adapter)

// Set default state
db.defaults({ items: [] })
  .write()

Now how it can be saved where it's hosted like in './maindb.json'? Is there anything available like FileSync?

Update

after realising there no way that client can access server filesystem. I probably asked a wrong question. but there is a solution using fetch. so if anyone has ans please put it down I am trying my best.

index.html -> fetch(jsonObj) -> post -> save.php-> creates maindb.json/updates.

index.html -> fetch() -> get -> save.php -> returns from maindb.json.

ANOL GHOSH
  • 1
  • 1
  • 9

1 Answers1

0

Controller.php

<?php 
class Controller {
    private $file = 'data.json',
            $jsondata = null,
            $tempArray = array(),
            $data= array();
    public function __construct() {
        $this->init();
    }
    private function init(){
        if (!file_exists($this->file)) {
            touch($this->file);
            $this->read();
        }else{
            $this->read();
        }
    }
    private function read(){
        $this->jsondata = file_get_contents($this->file);
        $this->tempArray = $this->jsondata != null ? json_decode($this->jsondata): array();
    }
    private function write(){
        array_push($this->tempArray, $this->data);
        $this->jsondata = json_encode($this->tempArray);
        file_put_contents($this->file, $this->jsondata);
    }
    public function push($data){
        $this->data = $data;
        if($this->data){
            $this->write();
            return true;
        }
    }
    public function get(){
        $this->read();
        return json_encode($this->tempArray);
    }
}
?>

json.php

<?php
require 'Controller.php';
$db = new Controller;
if($db->push($_POST['data'])){
    echo $db->get();
}
?>

javascript

function post(input){
    var data = {'data': input}
    $.ajax({
        type: 'POST',
        url: 'json.php',
        dataType: 'json',
        data: data,
        success: function(data) {
           console.log(data)
        }
    });
}
ANOL GHOSH
  • 1
  • 1
  • 9