The Dead Man
The Dead Man

Reputation: 5566

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?

Upvotes: 0

Views: 143

Answers (1)

Abdul Pathan
Abdul Pathan

Reputation: 355

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.

Upvotes: 2

Related Questions