When consuming RESTful services from a web client, jQuery and AJAX (Asynchronous JavaScript and XML) are commonly used to make HTTP requests and interact with RESTful APIs. The most common format for transferring data between the client and the server in REST APIs is JSON (JavaScript Object Notation).
In this guide, we'll cover how to perform CRUD (Create, Read, Update, Delete) operations using jQuery AJAX and JSON for consuming RESTful services.
Assuming the API you're consuming has endpoints like the following:
id.Let’s look at how to consume these operations using jQuery AJAX and JSON.
To add a new book, you would send a POST request with the book data (in JSON format) to the RESTful service.
$(document).ready(function () {
$('#addBookBtn').click(function () {
var bookData = {
title: $('#title').val(),
author: $('#author').val(),
year: $('#year').val()
};
$.ajax({
url: 'http://localhost:8080/api/books',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(bookData),
success: function (response) {
alert('Book added successfully!');
// Optionally reload the list of books after adding
loadBooks();
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
});
});
bookData object contains the details of the book that you want to add.$.ajax() method sends a POST request to the API endpoint.contentType is set to application/json because we're sending JSON data.data is the JSON stringified version of bookData.loadBooks(), which you will implement in the "Read" operation.To get all books, you would send a GET request to the /api/books endpoint.
function loadBooks() {
$.ajax({
url: 'http://localhost:8080/api/books',
type: 'GET',
dataType: 'json',
success: function (response) {
var booksList = $('#booksList');
booksList.empty(); // Clear the current list of books
response.forEach(function (book) {
booksList.append('<li>' + book.title + ' by ' + book.author + '</li>');
});
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
}
$(document).ready(function () {
loadBooks(); // Load books on page load
});
loadBooks() function sends a GET request to the /api/books endpoint.dataType: 'json').response) and display them in an unordered list (#booksList).To update an existing book, you would send a PUT request with the updated book data to the /api/books/{id} endpoint.
$(document).ready(function () {
$('#updateBookBtn').click(function () {
var bookId = $('#bookId').val(); // ID of the book to update
var bookData = {
title: $('#title').val(),
author: $('#author').val(),
year: $('#year').val()
};
$.ajax({
url: 'http://localhost:8080/api/books/' + bookId,
type: 'PUT',
contentType: 'application/json',
data: JSON.stringify(bookData),
success: function (response) {
alert('Book updated successfully!');
loadBooks(); // Reload the list of books
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
});
});
bookId is the ID of the book to be updated, taken from the input field #bookId.bookData object contains the updated data for the book.bookData as JSON to the /api/books/{id} endpoint.To delete a book, you would send a DELETE request to the /api/books/{id} endpoint, where id is the ID of the book to be deleted.
$(document).ready(function () {
$('#deleteBookBtn').click(function () {
var bookId = $('#bookId').val(); // ID of the book to delete
$.ajax({
url: 'http://localhost:8080/api/books/' + bookId,
type: 'DELETE',
success: function (response) {
alert('Book deleted successfully!');
loadBooks(); // Reload the list of books
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
});
});
bookId is the ID of the book to be deleted, taken from the input field #bookId./api/books/{id} endpoint.<!DOCTYPE html>
<html>
<head>
<title>Books CRUD Operations</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script> <!-- Include your script file -->
</head>
<body>
<h1>Books CRUD Operations</h1>
<!-- Create Book Form -->
<input type="text" id="title" placeholder="Book Title">
<input type="text" id="author" placeholder="Author">
<input type="number" id="year" placeholder="Year">
<button id="addBookBtn">Add Book</button>
<br><br>
<!-- Update Book Form -->
<input type="number" id="bookId" placeholder="Book ID to update">
<button id="updateBookBtn">Update Book</button>
<br><br>
<!-- Delete Book Form -->
<input type="number" id="bookId" placeholder="Book ID to delete">
<button id="deleteBookBtn">Delete Book</button>
<h2>Books List</h2>
<ul id="booksList"></ul>
</body>
</html>
With this setup, your HTML form allows you to create, read, update, and delete books using the corresponding AJAX operations. Each operation interacts with the REST API using JSON and jQuery.
Open this section to load past papers