AJAX (Asynchronous JavaScript and XML) in ASP.NET allows you to send and receive data from the server without having to reload the entire web page. It's commonly used to create more interactive and responsive web applications.
Client-Side Code (JavaScript): You use JavaScript to send requests to the server asynchronously (in the background) and handle the response without reloading the entire page.
Server-Side Code (ASP.NET): On the server side, you handle AJAX requests just like regular HTTP requests. You can process the request, retrieve data from a database, perform calculations, etc., and then send back a response.
Let's say you have a web page with a button, and when the user clicks the button, you want to fetch some data from the server and display it without refreshing the page.
HTML:
Example
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<button id="fetchDataBtn">Fetch Data</button>
<div id="result"></div>
<script>
$(document).ready(function () {
$("#fetchDataBtn").click(function () {
$.ajax({
url: "GetData.aspx", // URL to the server-side code
type: "GET", // HTTP method (GET or POST)
success: function (data) {
$("#result").html(data); // Display the response in the 'result' div
},
error: function () {
alert("An error occurred while fetching data.");
}
});
});
});
</script>
</body>
</html>
Example
using System;
using System.Web;
public partial class GetData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Simulate fetching data from a database
string data = "Data fetched from the server at " + DateTime.Now.ToString();
Response.Write(data);
}
}
In this example:
fetchDataBtn
is clicked, an AJAX request is sent to the server using jQuery's $.ajax()
function.GetData.aspx
) points to the server-side code that will handle the request.GetData.aspx.cs
) processes the request, simulates fetching data (in this case, just generating a timestamp), and sends the response back.result
div on the web page.This allows you to update parts of your web page dynamically without having to reload the entire page, providing a smoother and more interactive user experience.