How to Handle AJAX Calls in Selenium Webdriver
โก Smart Summary
AJAX calls update part of a page without a reload, so Selenium WebDriver must wait for the new content instead of assuming it is present, and the wait strategy decides whether the test passes reliably.
What is AJAX?
AJAX stands for Asynchronous JavaScript & XML, and it allows the Web page to retrieve small amounts of data from the server without reloading the entire page.
AJAX is a technique for building fast, dynamic web pages. It is asynchronous, combines JavaScript with a data format, and updates parts of a page instead of the whole page. Gmail, Google Maps, Facebook and YouTube all use it.
How AJAX Works?
For example, when you click a submit button, JavaScript sends a request to the server, interprets the result and updates the current screen without a reload. The diagram below shows that exchange.
- An AJAX call is an asynchronous request from the browser that does not cause a page transition. The user can keep working on the application while the request awaits a response.
- AJAX sends HTTP requests to the server and processes the response without reloading the page, so you cannot predict how long the server will take to answer.
From a tester’s point of view, checking content or an element means waiting until the response arrives. The payload was originally XML, as the name reflects; most APIs now return JSON.
How to Handle AJAX Calls in Selenium WebDriver
The biggest challenge in handling an AJAX call is knowing the loading time. Because the update lasts a fraction of a second, the application is hard to test through an automation tool, so Selenium WebDriver must apply a wait method to the call.
Executing that wait command suspends the current Test Case until the expected or new value appears; Selenium WebDriver then resumes the suspended steps.
Following are the wait methods that Selenium WebDriver can use
Thread.sleep()
- Thread.sleep () is not a wise choice as it suspends the current thread for the specified amount of time.
- In AJAX you can never be sure of the exact wait time, so the test fails if the element does not appear within it. It also adds overhead, because Thread.sleep(t) moves the current thread from the running queue to the waiting queue.
- After time ‘t’ the thread moves to the ready queue, and then waits again to be picked up by the CPU.
Note: the Java method is Thread.sleep() in lower case; the capitalised form does not compile.
Implicit Wait()
- This method tells WebDriver to wait when an element is not available immediately, and the setting stays in place for the whole browser session. Every element search can therefore take as long as the implicit wait allows.
Explicit Wait()
- Explicit wait is used to freeze the test execution till the time a particular condition is met or maximum time lapses.
WebDriverWait
- It can be used for any condition, by combining WebDriverWait with an ExpectedCondition.
- The best approach is to check the condition every second and move to the next command as soon as it is met.
But the problem with all these waits is, you have to mention the time out unit. What if the element is still not present within the time? So there is one more wait called Fluent wait.
Fluent Wait
- This is an implementation of the Wait interface with its own timeout and polling interval. Each FluentWait instance sets the maximum time to wait for a condition and how often to check it.
Challenges in Handling AJAX Call in Selenium WebDriver
- Using the “pause” command is not reliable. A long pause makes the test unacceptably slow and increases Testing time, so “waitforcondition” was recommended for AJAX applications instead.
- It is difficult to assess the risk associated with particular AJAX applications
- Giving developers full freedom to modify an AJAX application makes the testing process challenging
- Creating an automated test request can be hard for testing tools, because AJAX applications often use a different encoding or serialization technique to submit POST data.
Note: “pause” and “waitforcondition” are Selenese commands removed in Selenium 3; the WebDriver equivalent is an explicit wait.
Code Example for AJAX Handling using Selenium WebDriver
The TestNG class below reads the text, clicks the radio button, waits for the AJAX response and asserts that the text changed.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class Ajaxdemo { private String URL = "https://demo.guru99.com/test/ajax.html"; WebDriver driver; WebDriverWait wait; @BeforeClass public void setUp() { System.setProperty("webdriver.chrome.driver",".\\chromedriver.exe"); //create chrome instance driver = new ChromeDriver(); driver.manage().window().maximize(); driver.navigate().to(URL); } @Test public void test_AjaxExample() { By container = By.cssSelector(".container"); wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.presenceOfElementLocated(container)); //Get the text before performing an ajax call WebElement noTextElement = driver.findElement(By.className("radiobutton")); String textBefore = noTextElement.getText().trim(); //Click on the radio button driver.findElement(By.id("yes")).click(); //Click on Check Button driver.findElement(By.id("buttoncheck")).click(); /*Get the text after ajax call*/ WebElement TextElement = driver.findElement(By.className("radiobutton")); wait.until(ExpectedConditions.visibilityOf(TextElement)); String textAfter = TextElement.getText().trim(); /*Verify both texts before ajax call and after ajax call text.*/ Assert.assertNotEquals(textBefore, textAfter); System.out.println("Ajax Call Performed"); String expectedText = "Radio button is checked and it's value is Yes"; /*Verify expected text with text updated after ajax call*/ Assert.assertEquals(textAfter, expectedText); driver.close(); } }
Note: on Selenium 4 pass Duration.ofSeconds(5) to WebDriverWait and drop the System.setProperty line, because Selenium Manager resolves chromedriver.

