Below is the example to call certain URL with $.ajax() <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery AJAX Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#loadDataBtn").click(function() {
$.ajax({
url: "https://api.example.com/data", // URL to your API endpoint
type: "GET", // HTTP method (GET, POST, PUT, DELETE, etc.)
dataType: "json", // Expected data type from the server
success: function(data) {
// Callback function executed if the request succeeds
// 'data' contains the response from the server
console.log("Data loaded successfully:", data);
// You can process the 'data' here, for example, display it on the webpage
$("#result").html("<pre>" + JSON.stringify(data, null, 2) + "</pre>");
},
error: function(xhr, status, error) {
// Callback function executed if the request fails
console.error("Request failed:", status, error);
// You can handle errors here, for example, display an error message
$("#result").text("Error loading data. Please try again later.");
}
});
});
});
</script>
</head>
<body>
<button id="loadDataBtn">Load Data</button>
<div id="result"></div>
</body>
</html>
In this example: - The jQuery library is included via a CDN.
- The JavaScript code is enclosed within $(document).ready() to ensure it executes after the DOM is fully loaded.
- When the button with the ID loadDataBtn is clicked, an AJAX request is initiated using $.ajax().
- The request is a GET request to the URL "https://api.example.com/data".
- The dataType option is set to "json", indicating that we expect JSON data in response.
- If the request is successful, the success callback function is executed, where you can handle the response data.
- If the request fails, the error callback function is executed, where you can handle errors.
- In this example, the response data is displayed within the <div id="result">.
Tags: $.ajax() jQuery
|