JQuery Ajax with ajaxStart and ajaxComplete

From CoderLearner
Jump to: navigation, search

Description

  • $.ajaxStart() runs when Ajax starts.
  • $.ajaxComplete() runs when Ajax has completed.

ajaxStart()

  • The ajaxStart() method runs when an AJAX request starts.
  • Assign the 'Loading...' to the div#content_progress when the ajax request start
$('#content_progress').ajaxStart(function(){
	$(this).html('Loading...');
	$(this).fadeIn();
});

ajaxComplete()

  • ajaxComplete() method runs when the ajax REQUEST complete.
  • When the ajax complete, the div#content_progress disappears.
$('#content_progress').ajaxComplete(function(){
	$(this).fadeOut();
});

Example 1

<!DOCTYPE html>
<html>
   <head>
      <title>ajax</title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <script 
         type="text/javascript" 
         src="/lib/jquery-1.7.2.min.js">				 
      </script>
      <script>
         $(document).ready(function() {
            $('form[name="frm_userinfor"]').submit(function(){
               var agev = $('input[name="age"]').val();
         
               $.post('age.php',{'age':agev},
               function(data){
                  if(data=='failed'){
                     $('#content').html('Something wrong, please try again!');
                  }
                  else {
                     $('#content').html(data);
                  }
               });
               return false;
            });
            
            $('#content_progress').ajaxStart(function(){
               $(this).html('Loading...');
               $(this).fadeIn();
            });
            $('#content_progress').ajaxComplete(function(){
               $(this).fadeOut();
            });

         });
      </script>
   </head>
   <body>
      <div id="content_progress"></div>
      <div id="content"></div>
      <form name="frm_userinfor" method="post">
         Age:<input type="text" name="age"/><br/>
         <input type="submit" name="check" value="Check" />
      </form>
   </body>
</html>

Try It

Example 2

Create Table and Insert Records

CREATE TABLE user_profile
( 
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(200) NOT NULL,
  age INT NOT NULL,
  PRIMARY KEY(id)
);

INSERT INTO user_profile(name,age)
 VALUES('Bob',39),
       ('Jing',41),
       ('Paul',42),
       ('David',40),
       ('Jamy',20),
       ('Christ',28);

user_profile.php

<?php

define('HOST', 'localhost');
define('USER', 'user2000');
define('PASS', 'password2000');
define('DBNAME', 'w3cyberlearning');

$db = new mysqli(HOST, USER, PASS, DBNAME);
$age = $_GET['age'];
$result = array('error' => 'sure');
if (!empty($age)) {
	if ($db->connect_errno) {
		echo "Failed to connect to MySQL: (" 
         . $db->connect_errno . ") " . $db->connect_error;
	} else {
		$query =
		 "SELECT * FROM user_profile WHERE age >=?";
		$conn = $db->prepare($query);

		if ($conn) {
			$conn->bind_param("i", $age);
			$conn->execute();
			$conn->bind_result($id, $name, $age);

			$result = array();
			while ($row = $conn->fetch()) {
				$result[] = 
                               array(
                                  'id' => $id, 
                                  'name' => $name, 
                                  'age' => $age);
			}

			echo json_encode($result);
		}
		$conn->close();
	}
} else {
	echo json_encode($result);
}
$db->close();
?>

myjsonStart.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Profile List</title>
<script 
	type="text/javascript" 
	src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
	$(document).ready(function() {
	        $('form[name="frm_userinfor"]').submit(function(){
		    var userage = $('input[name="age"]').val();
				
		    $('#content_progress').ajaxStart(function(){
			$(this).html('Loading...');
			$(this).fadeIn();
		    });
		    $('#content_progress').ajaxComplete(function(){
			$(this).fadeOut();
		    });
		    $.ajax({
			url: 'user_profile.php',
			type:'GET',
			data:'age='+userage,
			dataType:'json',
			success:function(data){
		           if(data.error=='sure'){
			         $('#content').html('Error processing!');
			    }
			   else {
				var table = '<table border="1">';
				table += '<tr><td>User Id</td>'+
                                   '<td>User Name</td><td>User Age</td></tr>';
				$.each(data,function(i,element){
				    table +='</tr>';
				    table +='<td>'+ element.id + '</td>';
				    table +='<td>'+ element.name + '</td>';
				    table +='<td>'+ element.age + '</td>';
				    table +='</tr>';
				});
				table +='</table>';
				$('#content').html(table);
			    }
			}
		    });
		   return false;
	 });
});
</script>
</head>
<body>
	<div id="content_progress"></div>
	<div id="content"></div>
	<form name="frm_userinfor" method="post">
	    Age:<input type="text" name="age"/><br/>
	    <input type="submit" name="check" value="Check" />
	</form>
</body>
</html>