先輩エンジニアさんから教えていただいたjson形式ではないAjax通信を行います。
html/jqueryは以下の通り。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function() {
$('#ajax_post').click(function () {
var hogeValue = $('#hoge').val();
var someValue = $('#some').val();
$.ajax({
url: 'ajaxTest.php',
type: 'post',
data: "hoge="+hogeValue+"&some="+someValue
}).done(function(data){
/* 通信成功時 */
$('#ajax_show').text(data);
}).fail(function(data){
/* 通信失敗時 */
alert('通信失敗!');
});
});
});
</script>
</head>
<body>
<input type="text" id="hoge"><br>
<input type="text" id="some"><br>
<input type="button" id="ajax_post" value="送信">
<p id="ajax_show"></p>
</body>
</html>
json形式にするのって結構めんどくさいですよね。
いちいちjson形式にするほど大量のデータをやり取りしないときにいいと思います。
データベースとやり取りするときは結局Json形式で値は返ってきますが。
続いてphp。
<?php
$afterHoge = $_POST["hoge"];
$afterSome = $_POST["some"];
$afterWord = "";
$afterHoge .= '形式ではない';
$afterSome .= '通信成功!';
$afterWord = $afterHoge . $afterSome;
echo $afterWord;
これで簡単にフォームの値のやり取りを行います。
送信ボタンを押すと…
ちゃんとphpを通って返ってきました。