Asynchronous JavaScript and XML (AJAX)
AJAX is a technique used in web development that allows a webpage to send and receive data from a server asynchronously—without reloading the entire page.
Ajax is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not required (JSON is often used instead. See AJAJ), and the requests do not need to be asynchronous.
Ajax is not a single technology, but a group of technologies. HTML and CSS can be used in combination to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and allow the user to interact with, the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.
Why We Use AJAX?
Without AJAX: Every interaction → full page reload
With AJAX: Only part of the page updates dynamically
Examples:
• Live search suggestions
• Form submission without refresh
• Infinite scrolling
• Real-time dashboards
How AJAX Works?
• User interacts with a webpage
• JavaScript sends a request in the background
• Server processes the request
• Server returns data (usually JSON)
• JavaScript updates part of the page
Key Features of AJAX
• Asynchronous → doesn’t block the UI
• Partial updates → no full page reload
• Improved user experience
• Background data fetching
AJAX examples with C# backend
1. Simple ASP.NET Core API (C# Backend)
This is the server that AJAX will call.
Product model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
private static List<Product> products =
new List<Product>
{
new Product { Id = 1, Name = "Laptop" },
new Product { Id = 2, Name = "Phone" }
};
[HttpGet]
public IActionResult GetAll()
{
return Ok(products);
}
[HttpPost]
public IActionResult Add(Product product)
{
products.Add(product);
return Ok(product);
}
}
2. AJAX Example (JavaScript Frontend)
This calls the C# API without refreshing the page.
Using fetch (modern AJAX)
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
</head>
<body>
<h2>Products</h2>
<button onclick="loadProducts()">Load Products</button>
<ul id="list"></ul>
<script>
async function loadProducts() {
let response = await fetch("/api/products");
let data = await response.json();
let list = document.getElementById("list");
list.innerHTML = "";
data.forEach(p => {
let li = document.createElement("li");
li.innerText = p.name;
list.appendChild(li);
});
}
</script>
</body>
</html>
3. AJAX POST Example
Send data from browser → C# API
<script>
async function addProduct() {
let product = {
id: 3,
name: "Tablet"
};
let response = await fetch("/api/products", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(product)
});
let result = await response.json();
console.log("Added:", result);
}
</script>
4. jQuery AJAX (Older but still used)
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function loadProducts() {
$.ajax({
url: "/api/products",
type: "GET",
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
}
</script>
5. C# AJAX Helper (HttpClient Server-side call)
Sometimes “AJAX-like” calls are done from C# to another API:
using System.Net.Http;
using System.Text.Json;
HttpClient client = new HttpClient();
string json = await client.GetStringAsync("https://www.howcsharp.com/api/products");
var products = JsonSerializer.Deserialize<List<Product>>(json);
Console.WriteLine(products.Count);
Common Use Cases of AJAX
AJAX with C# backend is used for:
• live search
• chat applications
• dashboards
• form submission without refresh
• loading data tables
• notifications
• real-time UI updates
AJAX Best Practices
• Prefer fetch() instead of old jQuery AJAX
• Always return JSON from C# APIs
• Use proper HTTP status codes
• Use authentication (JWT) for secure endpoints
Advantages
• Faster and more responsive UI
• Reduced server load (less full-page rendering)
• Better user experience
• Enables dynamic web apps (like Gmail, maps, etc.)
Disadvantages
• More complex JavaScript code
• Harder debugging
• SEO challenges (if content loads dynamically)
• Requires careful error handling