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