K
K
kr_ilya2018-09-15 10:09:32
JavaScript
kr_ilya, 2018-09-15 10:09:32

How to write data to json file from form using Ajax?

I am making a tool, so to speak for myself, will be used on OpenServer.
I need to enter data into a json file through a form. It looks like this

[
    ["11.09.2018",222],
    ["12.09.2018",392],
    ["13.09.2018",485],
    ["14.09.2018",449],
    ["15.09.2018",449],
    ["16.09.2018",449],
    ["17.09.2018",449],
    ["18.09.2018",449]
]

There are 2 fields in the form: date and number.
How to implement all this via ajax so that new records are added in this format and at the end of the file?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Loginov, 2018-09-15
@kr_ilya

Given what you said about openServer, I suspect that you will have a backend in php.
1. Create a form

<form action="#" id="test">
    <input type="date" name="date">
    <input type="number" name="num">
    <input type="submit">
</form>

2. Send it via ajax
$(function(){

    $('#test').on('submit', function(){

        let data = $(this).serialize();

        $.ajax({
            method: 'POST',
            url: 'test.php',
            data: data
        }).done(function( msg ){
            console.log( msg );
        });

        return false;
    });
});

3. Add data to json file
$file = file_get_contents('data.json');
$list = json_decode($file,TRUE); 
unset($file);
$list[] = [ $_POST['date'], $_POST['num'] ];
file_put_contents('data.json',json_encode($list));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question