DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2
  • An Introduction to Type Safety in JavaScript With Prisma
  • OWASP TOP 10 API Security Part 2 (Broken Object Level Authorization)
  • Ultimate Guide to FaceIO

Trending

  • Designing Databases for Distributed Systems
  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • Agile Estimation: Techniques and Tips for Success
  1. DZone
  2. Coding
  3. JavaScript
  4. Strategies for dealing with multiple Ajax calls

Strategies for dealing with multiple Ajax calls

Raymond Camden user avatar by
Raymond Camden
·
Apr. 05, 15 · Interview
Like (0)
Save
Tweet
Share
8.39K Views

Join the DZone community and get the full member experience.

Join For Free

let’s consider a fairly trivial, but probably typical, ajax-based application. i’ve got a series of buttons:

shot1

each button, when clicked, hits a service on my application server and fetches some data. in my case, just a simple name:

shot2

the code for this is rather simple. (and note – for the purposes of this blog entry i’m keeping things very simple and including my javascript in the html page. please keep your html and javascript in different files!)

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
</head>
<body>

<button data-prodid="1" class="loadbutton">load one</button>
<button data-prodid="2" class="loadbutton">load two</button>

<div id="resultdiv"></div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
	$result = $("#resultdiv");
	
	$(".loadbutton").on("click", function(e) {
		var thisid = $(this).data("prodid");
		console.log("going to load product id "+thisid);
		$result.text("");
		$.getjson("service.cfc?method=getdata",{id:thisid}, function(res) {
			console.log("back with "+json.stringify(res));
			$result.text("product "+res.name);
		});
	});
});
</script>
</body>
</html>

i assume this makes sense to everyone as it is pretty boiler-plate ajax with jquery, but if it doesn’t, just chime in below in a comment. ok, so this works , but we have a small problem. what happens in the user clicks both buttons at nearly the same time? well, you would probably say the last one wins, right? but are you sure? what if something goes wrong (database gremlin – always blame the database) and the last hit is the first one to return?

untitled2

what you can see (hopefully – still kinda new at making animated gifs) is that the user clicks the first button, then the second, and sees first the result from the second button and then the first one flashes in.

now to be fair, you could just blame the user. i’m all for blaming the user. but what are some ways we can prevent this from happening?

one strategy is to disable all the buttons that call this particular ajax request until the request has completed. let’s look at that version.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
</head>
<body>

<button data-prodid="1" class="loadbutton">load one</button>
<button data-prodid="2" class="loadbutton">load two</button>

<div id="resultdiv"></div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
	$result = $("#resultdiv");
	
	$(".loadbutton").on("click", function(e) {
		//disable the rest
		$(".loadbutton").attr("disabled","disabled");
		var thisid = $(this).data("prodid");
		console.log("going to load product id "+thisid);
		$result.text("loading info...");
		$.getjson("service.cfc?method=getdata",{id:thisid}, function(res) {
			console.log("back with "+json.stringify(res));
			$(".loadbutton").removeattr("disabled");
			$result.text("product "+res.name);
		});
	});
});
</script>
</body>
</html>

i’ve added a simple call to disable all the buttons based on class. i then simple remove that attribute when the ajax request is done. furthermore, i also include some text to let the user know that – yes – something is happening – and maybe you should just calm the heck down and wait for it. the result makes it more obvious that something is happening and actively prevents the user from clicking the other buttons.

untitled3

another strategy would be to actually kill the existing ajax request. this is rather simple. the native xhr object has an abort method that will kill it, and jquery’s ajax methods returns a wrapped xhr object that gives us access to the same method.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
</head>
<body>

<button data-prodid="1" class="loadbutton">load one</button>
<button data-prodid="2" class="loadbutton">load two</button>

<div id="resultdiv"></div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>

$(document).ready(function() {
	$result = $("#resultdiv");

	var xhr;
	var active=false;

	$(".loadbutton").on("click", function(e) {
		var thisid = $(this).data("prodid");
		console.log("going to load product id "+thisid);
		$result.text("loading info...");
		
		if(active) { console.log("killing active"); xhr.abort(); }
		active=true;
		xhr = $.getjson("service.cfc?method=getdata",{id:thisid}, function(res) {
			console.log("back with "+json.stringify(res));
			$result.text("product "+res.name);
			active=false;
		});
	});
});
</script>
</body>
</html>

i use two variables, xhr and active, so that i can track when an active xhr request. there are other ways to track the status of the xhr object – for example, via readystate – but a simple flag seemed to work best. obviously you could do it differently but the main idea (“if active, kill it”), provides an alternative to the first method.

when using this, you can actually see the requests killed in dev tools:

untitled4

any comments on this? how are you handling this yourself in your ajax-based applications?

p.s. as a quick aside, brian rinaldi shared with me a cool little ui library that turns buttons themselves into loading indicators: ladda

Requests application code style Application server Object (computer science) JQuery JavaScript Indicator (metadata) Data (computing)

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2
  • An Introduction to Type Safety in JavaScript With Prisma
  • OWASP TOP 10 API Security Part 2 (Broken Object Level Authorization)
  • Ultimate Guide to FaceIO

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: