0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JS+PHP】ajaxでactionのデータを送ることで、関数の実行をコントロールする

Posted at

最近フロント側とバックエンド側との連携を作る時に、使っていた方法をメモしておく。関数が多いが、一つのファイルにまとめたい場合、使おうかな。
まずフロント側で、送信用formを用意する(ログインを例とする)

<?php
<form  id="id-name" method="POST">
//...
</form>
?>

ajaxでデータを送受信する

$(document).ready(function(){
    $("#id-name").submit(function(event){
        event.preventDefault(); // フォームの通常送信を防ぐ

        let id = $("#id").val();
        let password = $("#password").val();

        $.ajax({
            url: "/function.php",
            type: "POST",
            data: { id: id, password: password ,action: "login"},//ここでactionを追加で送る
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    window.location.href = "pages.php"; //成功時リダイレクト
                } else {
                    $("#error").text(response.message); //エラー表示
                }
            },
            error: function(xhr, status, error) {
                console.log("AJAXエラー: ", xhr, status, error);
                $("#error").text("通信エラーが発生しました");
            }
        });
    });
});

送られてきたactionloginであれば、ログインの関数を実行する

<?php
function login(){
//...
}
if (isset($_POST['action'])) {
    $action = $_POST['action'];

    switch ($action) {
    //actionがloginであれば実行する
        case 'login':
            login();
            break;

        case 'others':
            others();
            break;
            
        default:
            echo json_encode(["success" => false, "message" => "無効なアクション"]);
            break;
    }
} else {
    echo json_encode(["success" => false, "message" => "アクションが指定されていません"]);
}
0
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?