单击按钮时出现Ajax Loader - 代码出错

时间:2017-12-07 13:41:00

标签: jquery ajax forms

我已经按照其他建议显示了一个Ajax Loading Gif on按钮点击提交表单,但我似乎无法使代码正常工作。

非常感谢任何帮助。

    <p>
        <input type="hidden" name="job_manager_form" value="<?php echo $form; ?>" />
        <input type="hidden" name="job_id" value="<?php echo esc_attr( $job_id ); ?>" />
        <input type="hidden" name="step" value="<?php echo esc_attr( $step ); ?>" />

                    <?php if($job_id){ ?>
                    <img src="https://www.salusa.co.uk/wp-content/uploads/2017/12/ajax-loader.gif" id="img" style="display:none"/ >
                    <input type="submit" id="submitjob" name="submit_job" class="button" value="Update my service profile" />


                    <?php } else { ?>
                     <img src="https://www.salusa.co.uk/wp-content/uploads/2017/12/ajax-loader.gif" id="img" style="display:none"/ >
                    <input type="submit" id="submitjob" name="submit_job" class="button" value="Submit profile for admin approval" />
                    <?php } ?>

    </p>

<script>
                    $('#submitjob').click(function(){
                    $('#img').show();
                    $.ajax({
                    ....
                    success:function(result){
                    $('#img').hide();  //<--- hide again
}
}
</script>

1 个答案:

答案 0 :(得分:0)

如果您的Ajax请求有错误或者您没有包含jquery的必要脚本,则代码将不起作用。根据你上面所做的,我有一个工作的例子,请你参考:

<html>

<head>
  <title>Ajax Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>

<body>
  <input type="hidden" name="job_manager_form" value="<?php echo $form; ?>" />
  <input type="hidden" name="job_id" value="<?php echo esc_attr( $job_id ); ?>" />
  <input type="hidden" name="step" value="<?php echo esc_attr( $step ); ?>" />


  <!-- Here comes your if condition -->
  <img src="https://www.salusa.co.uk/wp-content/uploads/2017/12/ajax-loader.gif" id="img" style="display:none" />
  <input type="submit" id="submitjob" name="submit_job" class="button" value="Update my service profile" />

  <div id="content"></div>
</body>

<script>
  $('#submitjob').click(function() {
    $('#img').show();
    $.ajax({
      url: 'https://jsonplaceholder.typicode.com/posts/1',
      type: 'GET',

      error: function() {
        $('#content').html('<p>An error has occurred</p>');
      },
      dataType: 'json',
      success: function(result) {
        $('#content').html("data Received" + result);
        $('#img').hide(); //<--- hide again
      },
    });
  });
</script>
</body>

</html>