0

I am using jQuery and PHP to save content that the user inputs in a database. While the PHP is doing its thing I want to show a loading GIF image just to show that it is saving their data. I realize that it probably does take that long for it to run the code so i want to be able to show the image for at least 1 second if it takes less time than that

3
  • I want to eat a pack of Gushers. Have you tried anything? Commented Jul 20, 2012 at 21:06
  • 1
    JQuery beforeSend and success are your friends : api.jquery.com/jQuery.ajax Commented Jul 20, 2012 at 21:11
  • could you please expand on beforeSend! Commented Jul 20, 2012 at 21:16

1 Answer 1

1

For example, I'm using the following script as a live search form in a database.
The user types some letters and the script search if a student with that name exists in the database:

file index.php

<head>
//call to jquery.js
<script type='text/javascript'>
$(document).ready( function() {
 $('#q').keyup( function(){
  $field = $(this);
  $('#results').html('');
  $('#ajax-loader_e').remove();

  if( $field.val().length > 1 )
  {
    var str='q='+$(this).val();
    $.ajax({
      type : 'GET',
      url : 'ajax_search.php' ,
      data : str ,
      beforeSend : function() {
       $field.after('<img src="../img/ajax-loader.gif" alt="loader" id="ajax-loader_e" />');
      },
      success : function(data){
        $('#ajax-loader_e').remove();
        $('#results').html(data);
      }
    });//end ajax
  }//end if     
 });//end keyup
});//end ready
</script>
</head>
<body>
<form class="quick_search">
  <input type="text" value="Name" id="q" name="q" onfocus="if(!this._haschanged){this.value=''};this._haschanged=true;">
</form>
<div id="results_e"></div>

file ajax_search.php

if(isset($_GET['q'])){
  $nom='%'.safe($_GET['q']).'%';
  $req=$connexion->prepare("SELECT * FROM students WHERE name LIKE :name LIMIT 0,10 ");
  $req->execute(array('name'=>$name));
  echo "<ul>";
  while($row=$req->fetch(PDO::FETCH_ASSOC)){
    if(empty($row)){
      echo "<h4 class='alert_error'>No one with that name!</h4>";
    }
    else{
      echo "<li><strong><a href='?id=".$row['id']."'>".clean($row['nom']).' '.clean($row['prenom'])."</a></strong></li>";
    }
  }
  echo "</ul>";
}

You can use that script to save a form via ajax and display a loader gif while waiting. The important parts are:

  • remove the loader in the beginning
  • in beforeSend, display the loader
  • remove the loader in success
Sign up to request clarification or add additional context in comments.

1 Comment

ahh ok so just a beforeSend and success method to show and hide the image thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.