Handle Ajax Calls using Selenium Webdriver

In this Selenium tutorial, we’ll share some of¬†the best¬†techniques¬†to handle AJAX calls. You can apply them to your existing or new Selenium Webdriver projects. If your code manages AJAX elements¬†correctly, then it won’t throw false-positive failures due to operation timed-out.

AJAX is an advanced communication technique used by Web applications to exchange the data from the server without affecting the state of the currently opened web page. It saves the reloading of the page on the client-side and cuts down the number of requests on the server making it respond faster.

Because of these apparent advantages, many websites use AJAX calls to improve their user experience. But using the AJAX controls poses a challenge for the Selenium Webdriver as it gets only a fraction of seconds to act on the changes made by the AJAX calls.

What is AJAX and how does it work?

AJAX stands for “Asynchronous JavaScript and XML.”¬†It is a popular term in the context of dynamic web applications. Many people confuse it with a programming language. But it’s a technology that works with the combination of JS, CSS and, XML. It enables a web page to request the limited amount of information from the server without the need of refreshing the whole page.

You can consider an example when a user submits a form, the JavaScript dispatches the request to the server, process the response and update a part of the screen without refreshing the browser.

Handle Ajax Calls Using Selenium Webdriver,

How Ajax Call Communicates with the Web Server.


Some of the points which can be helpful in the testing of AJAX applications are as follows.

  • When a browser makes an AJAX call, it may not result in page¬†navigation. So you need to be careful what part of the page is getting changed by the server response.
  • AJAX calls are asynchronous and don’t¬†block the execution. So, the user can still use the¬†application until the server processes his request. For a tester, it would mean that he can’t estimate the actual time the server would take to deliver the response.

How to Handle AJAX calls using Selenium Webdriver?

You would now have an idea of the hurdles that¬†a tester could face while automating¬†a web page that makes AJAX calls. The main issue is how to handle the AJAX call when¬†you are not sure of the loading time of the webpage. Sometimes the change would be so sudden that it would disappear in a flash.¬†In this situation, you’ve to devise a strategy which should be dynamic and¬†perceptive.

So, let’s discuss the options¬†that we can deploy to handle AJAX calls in Selenium Webdriver.

1- Using <Thread.sleep(time in ms)> for handling AJAX controls.

<Thread.sleep()> is an obvious choice for handling AJAX calls. But it may not give you the best result. Instead, a test could break intermittently if the¬†server response time exceeds the time specified in sleep. Additionally, the test has to wait for the given time even in a situation of the timely response. Though keeping all the odds aside, this method does work, and we’ve tested it as working.


2- Using JavaScript to handle AJAX calls in Selenium Webdriver.

This method is only useful if the web application has jQuery in use to handle AJAX calls. Since jQuery uses a mechanism which keeps the no. of active AJAX calls in check, we can utilize this information to find out their final status.

Here is a sample code to showcase the handling of AJAX controls using Selenium Webdriver. You can integrate it into your test execution class.

	public void waitForAjaxControls(int timeoutInSeconds) {
				.println("Querying active AJAX controls by calling jquery.active");
		try {
			if (browser instanceof JavascriptExecutor) {
				JavascriptExecutor jsDriver = (JavascriptExecutor) browser;
				for (int i = 0; i < timeoutInSeconds; i++) {
					Object numberOfAjaxConnections = jsDriver
							.executeScript("return jQuery.active");
					// return should be a number
					if (numberOfAjaxConnections instanceof Long) {
						Long n = (Long) numberOfAjaxConnections;
								.println("Number of active jquery AJAX controls: "
										+ n);
						if (n.longValue() == 0L)
			} else {
				System.out.println("Web driver: " + browser
						+ " can't run javascript.");
		} catch (InterruptedException e) {


3- How to use Implicit wait to handle AJAX calls in Selenium Webdriver.

An implicit wait is a Webdriver mechanism to query the DOM for a specified time duration while locating one or more elements until they become available. The default timeout value is 0.

Once you define it, the implicit wait is available for the lifetime of the Webdriver instance.

WebDriver browser = new FirefoxDriver();
browser.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
WebElement ajaxControl = browser.findElement(By.id("DummyElement"));


4- How to use Webdriver Explicit wait for handling AJAX controls.

It is yet another Webdriver’s built-in feature to handle AJAX calls.¬†Just like the <Thread.sleep()>, you can get it working when no other tricks other work.

WebDriver browser = new FirefoxDriver();
WebElement ajaxControl = (new WebDriverWait(browser, 15))


5- Using Webdriver Fluent wait to handle AJAX calls.

It’s an implementation of the Webdriver’s Wait interface which brings both the timeout and polling interval to use. The¬†Fluent wait makes use of the timeout¬†to wait for a condition, also the frequency for the no. of attempts.

Its example you can see in the last section where we’ve demonstrated the combined use of <FluentWait> and the <WebdriverWait>.


6- Using <WebdriverWait> for handling the AJAX calls.

It is one of the best Webdriver strategies to handle the AJAX controls. It allows you to specify a condition to check at regular intervals and break to next step as soon as it gets timed out.

Apart from the <WebdriverWait>, we also use the <ExpectedCondition> to get the¬†entire mechanism in place. We’ve covered the detailed example in the next section.


Sample Code for Handling AJAX calls in Selenium Webdriver.

So far, you’ve seen six different strategies to work with the AJAX controls using Selenium Webdriver. In most of these methods, we’ve used various types of waits¬†to handle the AJAX calls.

Now, we’ll give¬†you a fully working demo of using the <FluentWait> and <WebdriverWait> for handling the AJAX controls.

We’ve used a w3schools.com’s demo website for testing the automation of AJAX calls.

AJAX Call Test Case Scenario.

Demo site used:

We’ve used the following demo URL for our testing which is using the AJAX calls.

  • [https://www.w3schools.com/xml/tryit.asp?filename=tryajax_callback]

Test Case Description:

  1. Open the demo AJAX application demo website.
  2. Following AJAX controls would appear in an IFRAME.
    1. A demo paragraph element which contains some default text.
    2. A simple button control to make the AJAX calls.
  3. When you click the button control, the AJAX call takes place.
    1. The default text disappears from the screen.
    2. Two new paragraphs get displayed on the screen.
  4. You now need to validate the two conditions.
    1. The new text in the first paragraph shouldn’t match the default text.
    2. The text in the second paragraph should match the expected value.

Note: We’ll¬†read the default text from the demo paragraph as it would appear first on the screen.¬†For the second paragraph, we’ve hardwired the value in the sample code which we copied from the demo test site.

Now, you’ll see the sample source code below. It should be self-explanatory as we’ve added comments¬†for each step.

Please set the above Demo URL in the <AJAX_TEST_URL> placeholder given before executing the code.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class AjaxTesting {

	private String ajaxTestSite = "<AJAX_TEST_URL>";

	WebDriver browser;
	WebDriverWait wait;

	public void startTest() {

		// Launch the demo web page to handle AJAX calls using Webdriver.
		browser = new FirefoxDriver();

	public void test_AjaxCalls() {

		/* Wait for the AJAX controls to appear. */
		By container = By.xpath(".//*[@id='demo']");
		wait = new WebDriverWait(browser, 5);

		/* Read the text that appears in the AJAX text control. */
		WebElement ajaxControl = browser.findElement(container);
		String ajaxTextFirstPara = ajaxControl.getText().trim();

		/* Click on the AJAX button control. */

		/* Wait for the new content to appear in the AJAX text control. */
		By newAjaxcontrol = By.xpath(".//*[@id='demo']/p");
		Wait<WebDriver> newwait = new FluentWait<>(browser)
				.withTimeout(60, TimeUnit.SECONDS)
				.pollingEvery(5, TimeUnit.SECONDS)

		 * Wait for the second paragraph value to get visible in the AJAX text
		 * control.
		WebElement secondParagraph = browser.findElement(By

		/* Get the text from the first paragraph after the AJAX call. */
		String ajaxNewTextFirstPara = browser

		/* Get the text from the second paragraph after the AJAX call. */
		String ajaxTextSecondPara = secondParagraph.getText().trim();
		String expectedTextInSecondPara = "AJAX is a technique for creating fast and dynamic web pages.";

		/* Verify the first paragraph text shouldn't match the new text. */
		Assert.assertNotEquals(ajaxTextFirstPara, ajaxNewTextFirstPara);

		/* Verify the second paragraph text must match with the new text. */
		Assert.assertEquals(ajaxTextSecondPara, expectedTextInSecondPara);

	public void endTest() {

If you wish to test the sample program then, add the above Java code to a TestNG project in Eclipse.¬†Whenever you run this program, it’ll execute successfully and produce the following report.

Test Report - Handle AJAX Calls Using Selenium Webdriver

Test Summary – Handle AJAX Calls Using Selenium Webdriver.


If you are reading this post and would like to appreciate our work or ask questions then, you are most welcome to share. If you knew an alternative technique for handling the AJAX calls then, we would love to hear it from you.

Please use the comment box and send us your views.


All the very Best,