LoginSignup
20
30

More than 5 years have passed since last update.

Ajax(jQuery)での通信中にローディング画像を表示する

Last updated at Posted at 2018-05-26

やりたいこと

Ajaxでサーバーと通信する際、くるくるのローディング画像を表示したい。

概要

  • beforeSend を使用する。これを使うことでajaxのリクエスト前に処理を実行させることができます。
  • php側は受け取った値をそのまま出力するだけのものとします。
    • ローディング画像を表示するために、sleep()で1秒ほど遅延させています。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>Ajax Test</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<style type="text/css">
body {
  margin-top: 100px;
  text-align: center;
}
.hide {
  display: none;
}
.loading {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0,0,0,.5);
  background-image: url(../img/712-88.gif);
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center center;
  background-size: 150px 150px;
}
</style>

  <form method="post" accept-charset="utf-8">
    <p>NAME: <input type="text" name="name" id="name"></p>
  </form>

  <button id="button1">POST</button>
  <div class="msg"></div>
  <div class="loading hide"></div>

  <script type="text/javascript">

    $(function() {
      $('#button1').on('click', function(){
        $.ajax({
          url: 'send.php',
          type: 'POST',
          data: {
            name: $('#name').val()
          },

          //リクエストが完了するまで実行される
          beforeSend: function(){
            $('.loading').removeClass('hide');
          }

        }).done(function(data){
          $('.loading').addClass('hide');          
          $('.msg').append('<p>NAME: ' + data + '</p>');

        }).fail(function(XMLHttpRequest, textStatus, errorThrown){
          console.log("failed...");
          console.log("XMLHttpRequest : " + XMLHttpRequest.status);
          console.log("textStatus     : " + textStatus);
          console.log("errorThrown    : " + errorThrown.message);
        });
      });
    });

  </script>
</body>
</html>
send.php
<?php
  sleep(1);

  header('Content-type: text/plain; charset=utf-8');
  if(isset($_POST['name'])) {
    $name = $_POST['name'];
    $msg = nl2br($name);
    echo $msg;
  } else {
    echo "FAILED.";
  }

実行結果

ajax_test.gif

Special Thanks

20
30
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
20
30