0
0

More than 3 years have passed since last update.

PHPとjqueryでJSONを使わないAjax通信をする

Last updated at Posted at 2021-01-18

先輩エンジニアさんから教えていただいた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;

これで簡単にフォームの値のやり取りを行います。

スクリーンショット 2021-01-18 22.09.07.png

送信ボタンを押すと…

スクリーンショット 2021-01-18 22.12.49.png

ちゃんとphpを通って返ってきました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0