画面から入力されたデータを php へ渡して json ファイルとして保存させる処理です。
入力値未記入でも保存はします。
(2016/09/15) : main.php を少し修正
■ test.php
※ js、css も直書きしてます
※ 年齢入力アラート付き(数字以外はエラー)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="content-language" content="ja">
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$(function() {
/* 年齢の入力チェック(数字以外はエラー) */
$("#input_age").change(function(){
$(".input_age_error").remove() ;
if(!$(this).val().match(/^(\d)*$/)) {
$("#input_age").after("<span class=\"error_message input_age_error\">数字を入れて</span>") ;
}
})
/* 保存ボタン押下したとき */
$("#save_button").on("click", function(){
$.post(
/* 動かす php */
"main.php"
, {
/* 送信パラメータ(入力値) */
name : $("#input_name").val()
, age : $("#input_age").val()
, gender : $("#input_gender").val()
}, function(data, status)
{
if(status == 'success') {
alert("保存しました") ;
}
}
) ;
})
})
</script>
<style>
.error_message
{
color : #FF0000 ;
margin : 0px 5px ;
}
#save_button
{
width : 100px ;
text-align : center ;
margin : 5px ;
padding : 5px 10px 5px 10px ;
border : 1px solid ;
}
#save_button:hover
{
cursor : pointer ;
background-color : #CCCCCC ;
}
</style>
<title>json 保存</title>
</head>
<body>
<div>
名前:<input type="text" id="input_name" />
</div>
<div>
年齢:<input type="text" id="input_age" maxlength="3"/>
</div>
<div>
性別:
<select id="input_gender">
<option value="1">男性</option>
<option value="2">女性</option>
</select>
</div>
<div id="save_button">保存</div>
</body>
</html>
■ main.php
※ json 保存処理。
※ 上書きではなく、追記していきます。
<?php
$json_data = array() ;
/* json 保存先ファイル */
$file = "data.json" ;
if(is_file($file) === false) {
/* 無ければ新規作成 */
touch($file) ;
chmod($file, 0777) ;
} else {
/* ある時は保存データを取得 */
$json_data = json_decode(file_get_contents($file), true) ;
}
$json_data[] = array(
"name" => $_POST["name"]
, "age" => $_POST["age"]
, "gender" => $_POST["gender"]
) ;
/* 書き込み */
file_put_contents($file, json_encode($json_data)) ;


