JQuery Ajax Http Delete remove data from SpringBoot RestAPI

In this tutorial, JavaSampleApproach will show you how to implement a web application which uses JQuery Ajax Http Delete to remove data from SpringBoot RestAPI.

Related posts:
Jquery Ajax POST-GET Nested Objects to SpringBoot server
Jquery Ajax PUT Nested Objects to SpringBoot server | Bootstrap
JQuery uses Bootstrap Table to display data from SpringBoot RestAPI
Ajax Jquery post List JavaScript Objects to SpringBoot server | BootStrap

I. Technologies

– Java 1.8
– Maven 3.6.1
– Spring Tool Suite – Version 3.8.1.RELEASE
– JQuery
– Bootstrap
– Spring Boot – 1.5.7.RELEASE

II. Practice

In the tutorial, we build a SpringBoot project as below:

JQuery Ajax Http Delete remove data with SpringBoot RestAPI - project structure

Step to do:
-Create Spring Boot project
– Create data models
– Create Web Controller to provide web view
– Create RestController for GET/DELETE request
– Create an index.html view
– Create JQuery Ajax DELETE request
– Run & Check results

1. Create Spring Boot project

Using Spring Tool Suite to create a Spring Starter Project. Add project info, then press Next for needed dependencies:

JQuery Ajax Http Delete remove data with SpringBoot RestAPI - dependencies

After creating project successfully, open pom.xml file and check needed dependencies:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. Create data models

– Create Address model:


package com.javasampleapproach.jquerydelete.model;

public class Address {
	 
	private String street;
	private String postcode;
	
	public Address(){}
	
	public Address(String street, String postcode){
		this.street = street;
		this.postcode = postcode;
	}
 
	public String getStreet() {
		return street;
	}
 
	public void setStreet(String street) {
		this.street = street;
	}
 
	public String getPostcode() {
		return postcode;
	}
 
	public void setPostcode(String postcode) {
		this.postcode = postcode;
	}
 
	@Override
	public String toString() {
		return "Address {street:" + street + ", postcode:" + postcode + "}";
	}
}

– Create Customer model that includes Address model:


package com.javasampleapproach.jquerydelete.model;

public class Customer {
	private String id;
	private String name;
	private Integer age;
	private Address address;
	
	public Customer(){}
	
	public Customer(String id, String name, Integer age, Address address){
		this.id = id;
		this.name = name;
		this.age = age;
		this.address = address;
	}
 
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public Integer getAge() {
		return age;
	}
 
	public void setAge(Integer age) {
		this.age = age;
	}
 
	public Address getAddress() {
		return address;
	}
 
	public void setAddress(Address address) {
		this.address = address;
	}
 
	@Override
	public String toString() {
		return "Customer {name:" + name + ", age:" + age + ", address:" + address + "}";
	}

}

3. Create Web Controller to provide web view


package com.javasampleapproach.angularjs.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class WebController {
 
	@GetMapping(value="/")
    public String homepage(){
        return "index";
    }
}

4. Create RestController for GET/DELETE request


package com.javasampleapproach.jquerydelete.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javasampleapproach.jquerydelete.model.Address;
import com.javasampleapproach.jquerydelete.model.Customer;


@RestController
@RequestMapping("/api/customer")
public class RestAPIs {
	
	Map custStores = new HashMap();
	
	@PostConstruct
    public void initIt() throws Exception {
        custStores.put("001", new Customer("001", "Jack", 25, new Address("NANTERRE CT", "77471")));
        custStores.put("002", new Customer("002", "Mary", 37, new Address("W NORMA ST", "77009")));
        custStores.put("003", new Customer("003", "Peter", 18, new Address("S NUGENT AVE", "77571")));
        custStores.put("004", new Customer("004", "Amos", 23, new Address("E NAVAHO TRL", "77449")));
        custStores.put("005", new Customer("005", "Craig", 45, new Address("AVE N", "77587")));
    }
	 
	@GetMapping(value = "/all")
	public List getResource() {
		
		List custList = custStores.entrySet().stream()
		        .map(entry -> entry.getValue())
		        .collect(Collectors.toList());
		
		return custList;
	}
	
	@DeleteMapping(value = "/delete/{id}")
	public String deleteCustomer(@PathVariable String id) {
		
		custStores.remove(id);
		return "OK!";
	}
}

5. Create an index.html view

<!DOCTYPE HTML>
 
<html>
<head>
      <title>Spring Boot - DELETE-UPDATE AJAX Example</title>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	  <script src="/js/jqueryAjaxGet.js"></script>
	  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>
 
<body>
<div class="container">
	<h1>Customer Table</h1>
		<div class="row col-md-7 table-responsive">
			<table id="customerTable" class="table table-bordered table-hover">
				<thead>
					<tr>
						<th>No</th>
						<th>Name</th>
						<th>Age</th>
						<th>Street</th>
						<th>Postcode</th>
					</tr>
				</thead>
				<tbody>
				</tbody>
			</table>
			
			<div id="resultMsgDiv">
			</div>
		</div>
	</div>
	
</body>
</html>

6. Create JQuery Ajax DELETE request


$(document).ready(function() {
	
	// Do GET all Customers from Back-End with JQUERY AJAX
	$(function () {
		$.ajax({
			type : "GET",
			url : window.location + "api/customer/all",
			success: function(result){
				$.each(result, function(index, customer){
					
					var customerRow = '' +
										'' + index + '' +
										'' + customer.name.toUpperCase() + '' +
										'' + customer.age + '' +
										'' + customer.address.street + '' +
										'' + customer.address.postcode + '' +
								        '' +
								        	'' +
								        	'' +
						          				'' +
						        			'' +
								        '' +
									  '';
					
					$('#customerTable tbody').append(customerRow);
					
		        });
				
				$( "#customerTable tbody tr:odd" ).addClass("info");
				$( "#customerTable tbody tr:even" ).addClass("success");
			},
			error : function(e) {
				alert("ERROR: ", e);
				console.log("ERROR: ", e);
			}
		});	
	});
	
	// Do DELETE a Customer via JQUERY AJAX
	$(document).on("click","a",function() {
		
		var customerId = $(this).parent().find('input').val();
		var workingObject = $(this);
		
		$.ajax({
			type : "DELETE",
			url : window.location + "api/customer/delete/" + customerId,
			success: function(resultMsg){
				$("#resultMsgDiv").html("

" + "Customer with Id=" + customerId + " is deleted successfully!" + "

"); workingObject.closest("tr").remove(); // re-css for table $( "#customerTable tbody tr:odd" ).addClass("info"); $( "#customerTable tbody tr:even" ).addClass("success"); }, error : function(e) { alert("ERROR: ", e); console.log("ERROR: ", e); } }); }); })

7. Run & Check results

Build & Run project with Spring Boot mode.
–> Result:

JQuery Ajax Http Delete remove data with SpringBoot RestAPI - logs

JQuery Ajax Http Delete remove data with SpringBoot RestAPI - results

III. Sourcecode

SpringBootJQueryHttpDelete

Leave a Reply

Your email address will not be published. Required fields are marked *