Reputation: 913
I have 4 input, which sent by Ajax 4 data, to a php file: how can I load json file and then add new data whih php?
<input type="text" id="name">
<input type="text" id="surname">
<input type="text" id="mobile">
<input type="text" id="email">
<script>
var name = $("#name").val();
var surname = $("#surname").val();
var mobile = $("#mobile").val();
var email = $("#email").val();
$.ajax({type:"POST",
url:"fill.php",
data:"name="+nombre+"&surname="+surname+"&mobile="+mobile+"&email="+email,
success:function(data) {
} }); JSON file: (people.json)
{
"1":
{
"Name" : "Jhon",
"Surname" : "Kenneth",
"mobile" : 329129293,
"email" : "[email protected]"
},
"2":
{
"Name" : "Thor",
"Surname" : "zvalk",
"mobile" : 349229293,
"email" : "[email protected]"
}
}
here I have a mistake fill.php file :
<?php
$name = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email =$_POST['email'];
$file = 'people.json';
$data = json_decode(file_get_contents($file));
$newdata = array('name'=>$name, 'surname' => $surname, 'mobile'=>$mobile,'email'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
?>
when I exeute it, it delete all the people.json date, and everytime that I add new data, it give me the next result: [{},{},{},{}]
Upvotes: 0
Views: 2464
Reputation: 3526
you need to add a secnod parameter to json_decode so it becomes an array, try this
<?php
$name = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email =$_POST['email'];
$file = 'people.json';
$data = json_decode(file_get_contents($file),1);
$newdata = array('name'=>$name, 'surname' => $surname, 'mobile'=>$mobile,'email'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
?>
Upvotes: 1
Reputation: 76
json decode accepts a second parameter, set it and you get arrays not stdClass objects.
Upvotes: 0