$.ajax()
method
The $.ajax()
method is a powerful and flexible way to make asynchronous HTTP requests using jQuery. It allows you to send and receive data to/from a server without reloading the page. This method can perform GET, POST, PUT, DELETE, and other HTTP methods, making it ideal for working with APIs or backend servers.
🔹 Syntax of $.ajax()
method:
$.ajax({
url: 'your-api-endpoint',
type: 'GET' | 'POST' | 'PUT' | 'DELETE',
data: { key1: 'value1', key2: 'value2' },
dataType: 'json', // expected data type from server
success: function(response) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
✅ Example: Using $.ajax()
to send a GET request
<!DOCTYPE html>
<html>
<head>
<title>$.ajax() Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="loadData">Load Data</button>
<div id="result"></div>
<script>
$('#loadData').click(function () {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1', // sample API
type: 'GET',
dataType: 'json',
success: function (data) {
$('#result').html(
`<h3>${data.title}</h3><p>${data.body}</p>`
);
},
error: function (xhr, status, error) {
$('#result').html("An error occurred: " + error);
}
});
});
</script>
</body>
</html>
📌 Key Points of $.ajax()
method:
- url: Endpoint where request is sent.
- type: HTTP method (e.g.,
GET
,POST
). - data: Data to be sent to the server.
- dataType: Expected data type of the response.
- success: Callback function when request is successful.
- error: Callback function when request fails.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.