Automating AJAX Calls in Selenium Java

Modern web applications often rely on AJAX (Asynchronous JavaScript and XML) to load content dynamically without refreshing the page. While this makes user experiences smooth and interactive, it also introduces challenges for automation testers. Since AJAX calls load data asynchronously, Selenium scripts must handle delays, dynamic content rendering, and timing issues carefully.

In this blog, we’ll explore how to automate AJAX calls in Selenium using Java, including best practices to wait for dynamic content, handle synchronization, and avoid flaky test cases.


๐Ÿง  What are AJAX Calls?

AJAX allows web applications to fetch data in the background and update parts of the UI without reloading the whole page. For example:

Loading search suggestions as you type

Updating cart items without reloading

Auto-refreshing dashboards

In Selenium, if your script tries to interact with an element before it has loaded (due to an AJAX request still running), it will throw a NoSuchElementException or ElementNotInteractableException.


๐Ÿ› ️ Strategy: How to Handle AJAX in Selenium Java

To successfully automate pages that use AJAX, you need to wait until the dynamic elements are ready. Here's how to do it.

✅ 1. Use Explicit Waits

Explicit waits are the most reliable way to handle AJAX content. Use WebDriverWait and ExpectedConditions to wait for specific elements to be present, visible, or clickable.

java


import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;


WebDriver driver = // Initialize driver

driver.get("https://example.com");


WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));

WebElement ajaxElement = wait.until(

    ExpectedConditions.visibilityOfElementLocated(By.id("ajax-loaded-element"))

);

ajaxElement.click();

This will pause the script until the AJAX-loaded element appears.


✅ 2. Wait for AJAX to Complete Using JavaScript

Sometimes, AJAX calls don’t directly result in new visible elements. In such cases, you can wait for the page’s AJAX activity to finish using JavaScript.


java


import org.openqa.selenium.JavascriptExecutor;


JavascriptExecutor js = (JavascriptExecutor) driver;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));


wait.until(webDriver -> (Boolean) js.executeScript("return jQuery.active == 0"));

Note: This works only if the site uses jQuery. For sites using fetch or XMLHttpRequest, you’ll need custom JS polling logic.


✅ 3. Wait for Element Text or Attribute Change

Some AJAX interactions update the text or value of elements (like counters or notifications). You can wait for the text to update:


java


wait.until(ExpectedConditions.textToBePresentInElementLocated(

    By.id("status"), "Completed"));

This ensures the AJAX request has updated the page before proceeding.


✅ 4. Avoid Thread.sleep()

Though tempting, using Thread.sleep(5000) is not recommended for handling AJAX calls. It leads to:

Unnecessary delays

Unstable tests (if AJAX takes longer)

Inefficient execution

Instead, always rely on smart waits like WebDriverWait.


๐Ÿงช Real-World Use Case

Imagine you’re testing a search feature that loads results via AJAX:

Enter a search keyword.

Wait for the results container to become visible.

Verify that results are displayed.


java

driver.findElement(By.id("searchBox")).sendKeys("laptops");

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("results")));

List<WebElement> results = driver.findElements(By.className("item"));

System.out.println("Found " + results.size() + " results.");

This structure ensures that Selenium waits for the asynchronous behavior to complete before asserting or interacting.


๐Ÿ”š Conclusion

AJAX adds complexity to web automation, but with the right techniques, you can reliably handle asynchronous content in Selenium Java. Use explicit waits, JavaScript-based checks, and avoid fixed delays to build robust, maintainable test scripts.

Mastering these patterns will help you automate dynamic modern web applications with confidence

 
Learn Selenium with Java  Course  in Hyderabad

Read More: Automating Double Click and Right Click Events in Selenium Java
Read More: Automating Web Tables in Selenium WebDriver Java
Read More: Generating Test Reports in Selenium Java Using ExtentReports

Visit Quality Thought Training Institute Hyderabad
Get Direction

Comments

Popular posts from this blog

Tosca vs Selenium: Which One to Choose?

Flask API Optimization: Using Content Delivery Networks (CDNs)

Using ID and Name Locators in Selenium Python