Ich bin ziemlich Anfänger mit JS, und ich habe noch nie PHP berührt. Nachdem ich stundenlang SO gewaschen habe, habe ich dieses Stück zusammengeschustert. Was ich versuche, ist ein einfaches Formular mit ein paar Feldern, die in einer JSON-Datei gespeichert werden. Ich möchte, dass jeder nachfolgende Eintrag an das Ende der Datei angehängt wird, sodass jedes JSON-Objekt der Name der Person und ihr Kommentar ist.Ajax> PHP> append json mit Formulardaten
Mit dem untenstehenden Code konnte ich erfolgreich etwas an das PHP-Skript übergeben und Einträge in die JSON-Datei anhängen. Aber was in der JSON-Datei auftaucht ist diese (nach zwei Einträge):
[{"data":"$data"},{"data":"$data"}]
Hier ist mein 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>
Mein 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();
});
});
Und mein 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);
}
?>
Danke
Ich weiß (ziemlich sicher) es etwas mit dem $ data [] = array ('data' => '$ data') zu tun hat; Linie, aber ich bin mir nicht sicher, wie man das handhabt – Aeromax
Variablen werden in doppelte Anführungszeichen, nicht einzelne Anführungszeichen erweitert. Genau wie 'bash' und' perl'. – Barmar
Sie brauchen keine Anführungszeichen um '$ data' herum. Benutze 'array ('data' => $ data)' – Barmar