Ajax > PHP > append json with form data

2019-09-07 01:44发布

I'm pretty beginner with JS, and I've never touched PHP before. After scouring SO for hours and hours, I've cobble together this piece. What I'm trying to do, is have a simple form with a couple of fields which get saved into a JSON file. I would like each subsequent entry to append to the end of the file, so that each JSON object is the person's name, and their comment.

With the below code, I've successfully been able to pass something to the PHP script, and append entries into the json file. But what shows up in the json file is this (after two entries):

[{"data":"$data"},{"data":"$data"}]

Here is my HTML

        <form method="POST">

            <!-- NAME -->
            <div id="name-group" class="form-group">
                <label for="name">Name</label>
                <input type="text" class="form-control" name="name" placeholder="">
                <!-- errors will go here -->
            </div>

            <!-- EMAIL -->
            <div id="comment-group" class="form-group">
                <label for="comment">Comment</label>
                <input type="text" class="form-control" name="comment" placeholder="">
                <!-- errors will go here -->
            </div>

            <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>

        </form>

My jquery

$(document).ready(function() {
    // process the form
    $('form').submit(function(event) {
        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'name'              : $('input[name=name]').val(),
            'comment'             : $('input[name=comment]').val(),
        };
        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'data/save.php', // the url where we want to POST
            data        : formData, // our data object
        })
            // using the done promise callback
            .done(function(data) {
                // log data to the console so we can see
                console.log(formData); 
                // here we will handle errors and validation messages
            });
        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });
});

And my PHP

<?php
if( !empty( $_POST ) ){
$data = json_encode( $_POST );
if( json_last_error() != JSON_ERROR_NONE ){
exit;  
}
$file = file_get_contents('comments.json');
$data = json_decode($file);
unset($file);
$data[] = array('data'=>'$data');
file_put_contents('comments.json',json_encode($data));
unset($data);
}

?>

Thanks

1条回答
Anthone
2楼-- · 2019-09-07 02:37

You're quoting $data, which prevents the variable from being expanded. You're also not putting the user input parameters into the array, you're trying to put the array into itself by using $data.

$data[] = array('name' => $_POST['name'], 'comment' => $_POST['comment']);

If you want to interpolate a variable into a string, you have to use double quotes, not single quotes. See What is the difference between single-quoted and double-quoted strings in PHP?

I don't see the point of the code that calls json_encode($_POST). That doesn't perform any useful validation of the post data, since anything that can be posted can be encoded.

There's also no need to use FormData in the Javascript. That's generally only needed if you're uploading a file. For other inputs, you can use the .serialize() method:

    var formData = $(this).serialize();
查看更多
登录 后发表回答