Wowsk
Wowsk

Reputation: 3675

Adding Objects to JSON file with JQuery

I have a very simple JSON file called json.php:

[ { "name":"wowsk" } ]

I want visitors to my website to be able to add objects to the array. What I am stuck on though is, how to allow them to add it. I have an HTML file and the body looks like this:

<form id="addName">
    <input id="name" placeholder="Enter your name.">
    <button id="addNameButton" type="submit">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
    function addName() {
        var input=document.getElementById("name").value;
        $.ajax({
        url: "json.php",
        type: 'POST',
        data:  {"name":"hello"}
    })
}
$("#addNameButton").click(function() {addName()}) 
</script>

The page will not add another object to the file though, and I have also tried using PUT but that does not work either. Will I not be able to use JQuery to add objects to the file or do I just have a mistake in using the function? I have researched this for multiple days but could not find anything to help.

Thanks for any help,
Wowsk

Also, as a note, I want the file to be changed for others too not just you or your session.

Upvotes: 2

Views: 1466

Answers (1)

adeneo
adeneo

Reputation: 318182

You'll need an actual PHP script that adds to the JSON file, it doesn't happen magically.

$.ajax({
    url  : "script.php",
    type : 'POST',
    data :  {"name":"hello"}
});

And then in script.php you'd do something like

<?php

    $content = file_get_contents('json.php');

    $json    = json_decode($content, true);

    $json["name"] = $_POST["name"] || "";

    $str     = json_encode($json);

    file_put_contents( 'json.php', $str );

?>

This is really verbose, but to make a point, you have to get the JSON, parse it into something usable, add the property, and then convert back to string, and store in the file again.

Upvotes: 2

Related Questions