In this tutorial, we will explore how to use jQuery and AJAX to interact with a REST service. AJAX (Asynchronous JavaScript and XML) allows us to send and receive data from a server asynchronously without the need to reload the entire page. With the help of jQuery, a popular JavaScript library, we can simplify and streamline our AJAX requests.
Prerequisites
To follow along with this tutorial, you will need the following:
- Basic knowledge of HTML, CSS, and JavaScript
- A REST service that supports the desired operations (GET, POST, PUT, DELETE)
- jQuery library included in your project (you can use a CDN or download it)
Coding the Rest Service Endpoint
Let’s start from the REST Endpoint:
@Path("customers") @ApplicationScoped @Produces("application/json") @Consumes("application/json") public class CustomerEndpoint { @Inject CustomerRepository customerRepository; @GET public List<Customer> getAll() { System.out.println("get all "); return customerRepository.findAll(); } @POST public Response create(Customer customer) { System.out.println("create " + customer); customerRepository.createCustomer(customer); return Response.status(Response.Status.CREATED).entity(customer).build(); } @PUT public Response update(Customer customer) { customerRepository.updateCustomer(customer); return Response.status(204).build(); } @DELETE public Response delete(@QueryParam("id") Long customerId) { customerRepository.deleteCustomer(customerId); return Response.status(204).build(); } }
As you can see, this REST Service contains CRUD methods to perform the basic operations on the Customer class. In this tutorial we will briefly cover the server-side. To learn more about REST Services check this article: Getting started with RESTEasy and WildFly
The Repository Class contains the methods to access the underlying database.
@ApplicationScoped public class CustomerRepository { @PersistenceContext private EntityManager entityManager; public List<Customer> findAll() { return entityManager.createNamedQuery("Customers.findAll", Customer.class) .getResultList(); } public Customer findCustomerById(Long id) { Customer customer = entityManager.find(Customer.class, id); if (customer == null) { throw new WebApplicationException("Customer with id of " + id + " does not exist.", 404); } return customer; } @Transactional public void updateCustomer(Customer customer) { Customer customerToUpdate = findCustomerById(customer.getId()); customerToUpdate.setName(customer.getName()); customerToUpdate.setSurname(customer.getSurname()); } @Transactional public void createCustomer(Customer customer) { entityManager.persist(customer); } @Transactional public void deleteCustomer(Long customerId) { Customer c = findCustomerById(customerId); entityManager.remove(c); } }
Finally, the Entity class which access the underlying H2 Database:
@Entity @NamedQuery(name = "Customers.findAll", query = "SELECT c FROM Customer c ORDER BY c.id") public class Customer { @Id @SequenceGenerator( name = "customerSequence", sequenceName = "customerId_seq", allocationSize = 1, initialValue = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customerSequence") private Long id; @Column(length = 40) private String name; @Column(length = 40) private String surname; // Getters and Setters omitted for brevity }
Done with the server side. Now let’s add an index.hml page to display the List of Customers in an HTML Table.
Coding the Ajax JQuery Layer
First, let’s set up our HTML file and include the jQuery library:
<!DOCTYPE html> <html> <head> <title>REST Service Interaction with jQuery and AJAX</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <!-- Your HTML content here --> </body> </html>
Then, we will write the javascript part which contains the JQuery functions to perform the POST and GET requests:
<script> $(document).ready(function() { // Get all customers on page load getAllCustomers(); // Handle form submission $("#addCustomerForm").submit(function(event) { event.preventDefault(); var name = $("#name").val(); var surname = $("#surname").val(); // Create customer createCustomer(name, surname); // Clear form inputs $("#name").val(""); $("#surname").val(""); }); }); function getAllCustomers() { $.ajax({ url: "rest/customers", type: "GET", dataType: "json", success: function(customers) { displayCustomers(customers); }, error: function() { console.log("Error occurred while retrieving customers."); } }); } function createCustomer(name, surname) { var customer = { name: name, surname: surname }; $.ajax({ url: "rest/customers", type: "POST", dataType: "json", contentType: "application/json", data: JSON.stringify(customer), success: function () { console.log("Customer created successfully."); getAllCustomers(); // Refresh the customer list }, error: function (xhr, textStatus, errorThrown) { console.log("Error occurred while creating a customer: " + errorThrown); } }); } function displayCustomers(customers) { var customerList = $("#customerItems"); customerList.empty(); customers.forEach(function(customer) { var listItem = $("<li>").text("ID: " + customer.id + ", Name: " + customer.name + ", Surname: " + customer.surname); customerList.append(listItem); }); } </script>
And finally, include the HTML form to list Customers and add a new Customer:
<h1>Customer Management</h1> <div id="customerList"> <h2>Customers:</h2> <ul id="customerItems"></ul> </div> <h2>Add Customer:</h2> <form id="addCustomerForm"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <label for="surname">Surname:</label> <input type="text" id="surname" name="surname"> <button type="submit">Add</button> </form>
A deep look inside the jQuery Ajax methods
- The
$(document).ready()
function is a jQuery event handler that is triggered when the document (web page) has finished loading. It ensures that the JavaScript code inside the function is executed only when the document is ready. - Inside the
$(document).ready()
function, thegetAllCustomers()
function is called to fetch and display all customers when the page is loaded. This function makes a GET request to the REST service endpoint/rest/customers
using the$.ajax()
method. - The
$("#addCustomerForm").submit()
function is another jQuery event handler that is triggered when the “Add” button in the form is clicked. It prevents the default form submission behavior and instead calls thecreateCustomer()
function. - The
createCustomer()
function retrieves the values from the “Name” and “Surname” input fields and creates acustomer
object with those values. It then makes a POST request to the REST service endpoint/rest/customers
using the$.ajax()
method. Thecustomer
object is sent as JSON data in the request body using theJSON.stringify()
method. - If the customer creation is successful, the
success
callback function inside the$.ajax()
method is executed. It logs a success message to the console, callsgetAllCustomers()
to refresh the customer list, and clears the form inputs. - If there is an error in customer creation, the
error
callback function inside the$.ajax()
method is executed. It logs an error message with the specific error details to the console. - The
displayCustomers()
function takes an array of customers as input and dynamically generates HTML list items (<li>
) based on the customer data. It appends the list items to the customer list (<ul>
) in the web page.
Building and deploying the application
Deploy the application on WildFly with:
$ mvn package wildfly:deploy
Now you can access the index.html page at http://localhost:8080/jaxrs-demo/index.html add a new Customer :
Conclusion
Congratulations! You have successfully learned how to integrate jQuery, AJAX, and REST services in your web applications. By combining the power of these technologies, you can create dynamic and interactive web pages that communicate seamlessly with RESTful APIs.
By leveraging the flexibility and simplicity of jQuery and AJAX, you can create responsive and interactive web applications that communicate seamlessly with RESTful services. This integration opens up a wide range of possibilities for building robust and efficient web solutions.
Source code: https://github.com/fmarchioni/mastertheboss/tree/master/jax-rs/jquery