How to integrate JQuery Ajax and REST Services

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.


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:

public class CustomerEndpoint {

    @Inject CustomerRepository customerRepository;

    public List<Customer> getAll() {
        System.out.println("get all ");
        return customerRepository.findAll();
    public Response create(Customer customer) {
        System.out.println("create " + customer);
        return Response.status(Response.Status.CREATED).entity(customer).build();

    public Response update(Customer customer) {
        return Response.status(204).build();
    public Response delete(@QueryParam("id") Long 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.

public class CustomerRepository {

    private EntityManager entityManager;

    public List<Customer> findAll() {
        return entityManager.createNamedQuery("Customers.findAll", Customer.class)

    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;
    public void updateCustomer(Customer customer) {

        Customer customerToUpdate = findCustomerById(customer.getId());
    public void createCustomer(Customer customer) {


    public void deleteCustomer(Long customerId) {

        Customer c = findCustomerById(customerId);


Finally, the Entity class which access the underlying H2 Database:

@NamedQuery(name = "Customers.findAll",
        query = "SELECT c FROM Customer c ORDER BY")
public class Customer {
            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>
    <title>REST Service Interaction with jQuery and AJAX</title>
    <script src=""></script>
    <!-- Your HTML content here -->

Then, we will write the javascript part which contains the JQuery functions to perform the POST and GET requests:

        $(document).ready(function() {
            // Get all customers on page load
            // Handle form submission
            $("#addCustomerForm").submit(function(event) {
                var name = $("#name").val();
                var surname = $("#surname").val();
                // Create customer
                createCustomer(name, surname);
                // Clear form inputs
        function getAllCustomers() {
                url: "rest/customers",
                type: "GET",
                dataType: "json",
                success: function(customers) {
                error: function() {
                    console.log("Error occurred while retrieving customers.");
        function createCustomer(name, surname) {
          var customer = {
          name: name,
          surname: surname

        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");
            customers.forEach(function(customer) {
                var listItem = $("<li>").text("ID: " + + ", Name: " + + ", Surname: " + customer.surname);

And finally, include the HTML form to list Customers and add a new Customer:

<h1>Customer Management</h1>

<div id="customerList">
    <ul id="customerItems"></ul>

<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>

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, the getAllCustomers() 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 the createCustomer() function.
  • The createCustomer() function retrieves the values from the “Name” and “Surname” input fields and creates a customer object with those values. It then makes a POST request to the REST service endpoint /rest/customers using the $.ajax() method. The customer object is sent as JSON data in the request body using the JSON.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, calls getAllCustomers() 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 :

jquery integration with ajax and rest services


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: