1

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:"wjson.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]"
    }
}

wjson.php file :

<?php
$nane = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email =$_POST['email'];
$str_datos = file_get_contents("people.json")
//add new data to people.json
?>

by the way people.json file is in my server

1 Answer 1

10

You can do it like this:

// Loading existing data:
$json = file_get_contents("people.json");
$data = json_decode($json, true);

// Adding new data:
$data[3] = array('Name' => 'Foo', 'Surname' => 'Bar');

// Writing modified data:
file_put_contents('people.json', json_encode($data, JSON_FORCE_OBJECT));

However, reading and writing a blob of possibly large size just to add a small item or two is not the best idea. If your dataset starts growing, consider alternative solutions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.