简体   繁体   中英

How to save JSON data to new JSON file through iterating using AJAX and PHP?

I have simple movies editor with the sidebar in which user just drag and drop the element to the right side user can edit this element as they wish and save data to JSON, I want when the user clicks to save it should create a new file and save to it new data.

so far here is what I have

HTML

        <div class="col-2 save-details">
          <div id="save-block">
            <button type="button" class="btn btn-success btn-save">Save</button>
          </div>
        </div>

here is js to save the file

var moviesblocks =null;

$(document).ready(function(){

$.getJSON('moviesblocks.json', function (data) {

    moviesblocks = data.moviesblocks;
    console.log(moviesblocks);

});

$("#main-btn-save").on("click", function () {

    var moviesparams = JSON.stringify({
        moviesblocks: moviesblocks
    });

    $.ajax({
            type: 'POST',
            data: {
                moviesparams: moviesparams
            },
            url: 'save_movies_block.php',
            success: function (data) {
                    $('#msg').html(data).fadeIn('slow');
                    $('#msg').delay(2000).fadeOut('slow');
            },
            error: function () {
                    $('#error-msg').html(data).fadeIn('slow');
                    $('#error-msg').delay(2000).fadeOut('slow');
            }
    });

    console.log(moviesparams);
});

})

Here is php file to handle the process

<?php
if(isset($_POST['moviesparams'])){
    $moviesparams = json_decode($_POST['moviesparams']);
    // do whatever checks you need on $moviesparams to verify valid data
    $success = file_put_contents("moviesblocks.json", json_encode($moviesparams));
    if($success === false){
        echo "sorry , something is wrong";
        die();
    }else{
        echo "Data successfully saved";
        die();
    }
} else {
    echo "nic";
}

$data=file_get_contents("data.json");
$result=json_decode($data);
?>

As you can see now after user clicks save it save to this file

moviesblocks.json

Now I want when a user clicks save, it should save to new file something like moviesblocks1.json instead of moviesblocks.json

Here is a live demo live demo

How can I achieve what I want?

If you dont wanna use database, you need to create one more file to maintain file version numbers. Each time you wanna create new file, get the latest version number from this version.txt file and append it to filename. Eg : moviesblocks1.json, moviesblocks2.json.

After creating new file, update the version from version.txt. This will help you to create new version number next time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM