D. Gatch
D. Gatch

Reputation: 167

How to insert data into json from an html form

I was able to get the json file through this code:

<?php
include "lib/lib.php";

$url = "http://10.0.0.1/lib/api/desk/";

$params = array ("action" => "list","company_key" => "1");

$result=requestURL($url,$params);

$json_a=json_decode(strip_tags($result)); 
?>

The result of that is:

{
    "data": [
        {
            "id": "18",
            "name": "SM Quezon",
            "branch_address": "Quezon City, Philippines",
            "officer_in_charge": "Juan Dela Cruzz",
            "contact_number": "09321234567, 02-3449067"
        }
    ]
}

I have a form which should function to add data array to a json file. What should happen is that after submitting the form, the inserted data will now be included in json file.

<div class="modal-body">
<form id="form" onsubmit="alert('save?')" method="post">
    <div class="modal-body">
        <label class="control-label">Name</label>
        <input type="text" class="form-control" id="Name" />
        <label class="control-label">Branch Address</label>
        <input type="text" class="form-control" id="BranchAddress" />
        <label  class="control-label">Officer-in-Charge</label>
        <input type="text" class="form-control" id="OfficerInCharge" />
        <label  class="control-label">Contact Number</label>
        <input type="text" class="form-control" id="ContactNumber" />
    </div>
    <div class="modal-footer">
        <input id="submit" type="submit" value="SUBMIT" class="btn" />
    </div>
</form>

How will I be able to insert the data I have from the form to json file?

Upvotes: 1

Views: 3493

Answers (1)

Kalamun
Kalamun

Reputation: 429

First of all, the form: the "Save changes" button must be inside the <form> tag.

    <form>....
    <input type="submit" value="Save changes">
    </form>

Second step: inside the form you must add some fields.

<form>
Name: <input type="text" name="name"><br>
Address: <input type="text" name="address"><br>
...
</form>

Third step: declare "action" and "method" on your form.

<form action="" method="post">

So at the end the form will be something like this:

<form action="" method="post">
Name: <input type="text" name="name"><br>
Address: <input type="text" name="address"><br>
<input type="submit" value="Save changes">
</form>

SAVE the INPUT FIELDS

<?php
include "lib/lib.php";
$url = "http://10.0.0.1/lib/api/desk/";
$params = array ("action" => "list","company_key" => "1");
$result=requestURL($url,$params);
$json_a=(array)json_decode(strip_tags($result)); 

$newdata=array();
foreach($_POST as $key=>$value) {
    $newdata[$key]=$value;
}
$json_a['data'][]=$newdata;

$json_a=json_encode($json_a);
?>

After that you will have a JSON object with included the new data. I suppose that you must save it somewhere.

Upvotes: 1

Related Questions