Tag Archive for Cancel Operation using Ajax

Pause and Cancel Operation using Ajax

Recently I came accross the situation when I need to upload zip file containing multiple files and have to compute some operation for each file. The upload process could be achieved easily using ajax file upload. But the part that obstruct me is the pause and cancel operation in ajax.

I googled it a lot and there is no single tutorial on that topic. So, I decided to write it myself. Below is just the code snippet for pause and cancel operation. You have to call the ajax request function recursively in order to achieve this operation until all the queue are processed. It checks the pause status and only operates if the process is resume. The code should be fairly simple and self explanatory.

<script>
$(document).ready(function() {
	var xhr;
	var pause = false;
	var counter = 0;
	var lastEncounter = 0;
	var arr = ["1","2","3","4"];
				
	function myAjaxRequest(value) {	
		if(!pause) {
			lastEncounter = value;
			xhr = $.ajax({
				url: 'test.php',
				type: 'GET',
				data: "",
				success: function(data) {
					counter++;		
					if(counter < arr.length) {
						myAjaxRequest(arr[counter]);
					}
				}							                    
       });				
		}					
	}
				
	$("#start").click(function(e) {	
		myAjaxRequest(arr[0]);				
	});				
						
	$("#cancel").click(function(e) {
		xhr.abort();
	});
				
	$("#pause").click(function(e) {
		pause = true;
	});
				
	$("#resume").click(function(e) {
		pause = false;
		myAjaxRequest(lastEncounter + 1);
	});
});
</script>

<input type="button" value="Start" id="start">
<input type="button" value="Cancel" id="cancel">
<input type="button" value="Pause" id="pause">
<input type="button" value="Resume" id="resume">
www.000webhost.com