form送信方法 #HTML #javascript

基本知識

HTMLからサーバーサイドプログラムへのデータ送信

submitイベント発火時に、formで囲まれたname属性で指定した名前とvalue属性の値が一組になって送信される.
action属性:フォーム経由で送信された情報を処理するプログラムの URI.
method属性:フォームを送信する際にブラウザーが使用するHTTPメソッド.

$_POST, $_GET

PHPの関数で、HTTPで取得した値を連想配列で取得する.

標準出力関数

PHPでは、下記の関数が提供されている.
echo, var_dump, print_r, var_export 
サーバーサイドプログラムで処理した結果等をブラウザに表示する際に用いる.

非同期通信(Ajax

サーバーとの通信, データの交換, ページの更新を, ページの再読み込みなしに行うことができる.

form送信方法

1. HTMLのsubmit属性の利用

1-1. 単一form

<html>
  <head><meta charset="utf-8"></head>
  <body>
    <form action="index.php" method="post">
      <input type="text" id="text" name="text" value="">
      <button type="submit" name=button" value="input">送信</button>
      <!--
       * input要素での記述は下記のとおり.
       * <input type="submit" name="button" value="送信">
      -->
    </form>
  </body>
</html>

1-2. 複数form

<html>
  <head><meta charset="utf-8"></head>
  <body>
    <form action="index1.php" method="post">
      <input type="text" id="text" name="text" value="">
      <button type="submit" name=button1" value="input">送信</button>
      <!--index1.phpにデータが送信される.-->
    </form>
    <form action="index2.php" method="post">
      <input type="text" id="text" name="text" value="">
      <button type="submit" name=button2" value="input">送信</button>
      <!--index2.phpにデータが送信される.-->
    </form>
  </body>
</html>

2. javascriptの利用

2-1. submit関数

<html>
  <head><meta charset="utf-8"></head>
  <body>
    <form action="index1.php" method="post">
      <input type="text" name="text" value="">
      <button id="button" value="input">送信</button>
    </form>
    <script src="http://code.jquery.com/jquery.js"></script>
    <script>
      $(function(){
        $('button').click(function(){
          $('form').submit();
        });
      })
    </script>
  </body>
</html>

2-2. Ajax

<html>
  <head><meta charset="utf-8"></head>
  <body>
    <form>
      <input type="text" id="text" name="text" value="">
      <button type="button" id="button" name="button" value="input">送信</button>
    </form>
  <script src="http://code.jquery.com/jquery.js"></script>
  <script>
    $(function(){
      $('#button').click(function(){
        $.ajax({
          url: 'http://localhost:8080/index1.php',
          type: 'post',
          data: $('form').serialize(), // form内のtype属性がbutton, submitのデータ以外が送信される.
          /* 送信するデータを指定する場合
             data: {
               text: $('#text').val()
             },
          */
          timeout: 10000,
        })
        .then(
        function(data) {
          // 通信が成功したときの処理
          document.write(data); // index1.phpで処理された結果でhtmlを書き換える.
        },
        function(data) {
          // 通信が失敗したときの処理
        });
      });
    });
  </script>
  </body>
</html>

サーバーサイドプログラム

index1.php

<?php
  echo('index1.php:サーバーサイドプログラムにデータが送信されました.');
  echo nl2br("\n");
  var_dump($_POST);
?>

index2.php

<?php
  echo('index2.php:サーバーサイドプログラムにデータが送信されました.');
  echo nl2br("\n");
  var_dump($_POST);
?>