Ajax Jquery post List JavaScript Objects to SpringBoot server | BootStrap

In the tutorial, JavaSampleApproach will guide you how to create a web application Ajax Jquery post List JavaScript Objects to SpringBoot server.

Related posts:
JQuery Ajax Http Delete remove data from SpringBoot RestAPI
Jquery Ajax POST-GET Nested Objects to SpringBoot server
Html5 DateTime + Ajax Jquery + SpringBoot @JsonFormat example

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

We create a SpringBoot project as below:

Ajax Jquery post List JavaScript Objects to SpringBoot server - project structure

Run and check results:

-> adding form:

Ajax Jquery post List JavaScript Objects to SpringBoot server - add customer form

Ajax Jquery post List JavaScript Objects to SpringBoot server - add list of customers

-> post data:

Ajax Jquery post List JavaScript Objects to SpringBoot server - post list of customers logs

Ajax Jquery post List JavaScript Objects to SpringBoot server - post list of customers

-> get data:

Ajax Jquery post List JavaScript Objects to SpringBoot server - get list of customers logs

Ajax Jquery post List JavaScript Objects to SpringBoot server - view results

III. Practice

Step to do:
– Create SpringBoot project
– Create data models
– Create Web Controller to provide web view
– Create RestController for GET/POST requests
– Create an index.html view
– Create JQuery Ajax POST/GET requests

1. Create SpringBoot project

Using Spring Tool Suite to create a Spring Starter Project with needed dependencies:


	org.springframework.boot
	spring-boot-starter-thymeleaf


	org.springframework.boot
	spring-boot-starter-web

2. Create data models

– Create Address model:

package com.javasampleapproach.jquery.postlistobjects.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.jquery.postlistobjects.model;

public class Customer {
	private String name;
	private Integer age;
	private Address address;
	
	public Customer(){}
	
	public Customer(String name, Integer age, Address address){
		this.name = name;
		this.age = age;
		this.address = address;
	}
 
	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.jquery.postlistobjects.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/POST requests
package com.javasampleapproach.jquery.postlistobjects.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javasampleapproach.jquery.postlistobjects.model.Customer;

@RestController
@RequestMapping("/api/customer")
public class RestWebController {
	
	List cust = new ArrayList();
	
	@GetMapping(value = "/all")
	public List getResource(){
			return cust;
	}
	
	@PostMapping(value="/save")
	public String postCustomer(@RequestBody List customers){
		cust.addAll(customers);
		return "Post Successfully!";
	}
}
5. Create an index.html view

 


	  Spring Boot - AJAX POST GET Example
	  
	  
	  %MINIFYHTML0dcc0205b80d0343ce88b9c4df2e3ddd16%%MINIFYHTML0dcc0205b80d0343ce88b9c4df2e3ddd17%%MINIFYHTML0dcc0205b80d0343ce88b9c4df2e3ddd18%%MINIFYHTML0dcc0205b80d0343ce88b9c4df2e3ddd19%

 

POST-GET AJAX NESTED OBJECT

No Name Age Street Postcode
%MINIFYHTML0dcc0205b80d0343ce88b9c4df2e3ddd20%
6. Create JQuery Ajax POST/GET requests

– Create postrequest.js file:

$( document ).ready(function() {
	
	var listCustomers = [];

	/**
	 * Using JQuery for hiding some elements in view when bootstrap app
	 */
	// Hide customer table when starting
	// we just show it if having any adding-customer
	$('#customerTable').hide();
	$('#postCustomersBtn').hide();
	
	// Customer-Form submit
    $("#customerForm").submit(function(event) {
		// Prevent the form from submitting via the browser.
		event.preventDefault();
		
		// get data from submit form
		
		var formCustomer = {
    			name : $("#name").val(),
    			age : $("#age").val(),
    			address : {
    		    	street : $("#street").val(),
    		    	postcode : $("#postcode").val()
    		    }
    	}
		
		// store customer
		listCustomers.push(formCustomer);
		
		// re-render customer table by append new customer to table
		
		var customerRow = '' +
							'' + listCustomers.length + '' +
							'' + formCustomer.name.toUpperCase() + '' +
							'' + formCustomer.age + '' +
							'' + formCustomer.address.street + '' +
							'' + formCustomer.address.postcode + '' +
					        '' +
					        	'' +
					        	'' +
					  				'' +
								'' +
					        '' +
						  '';

		$('#customerTable tbody').append(customerRow);

		// just how customer table and POST button
		$('#customerTable').show();
		$('#postCustomersBtn').show();
		
		// Reset FormData after Posting
    	resetData();
	});
    
	// Do DELETE a Customer via JQUERY AJAX
	$(document).on("click","a",function() {
		var customerId = $(this).parent().find('input').val();
		$(this).closest("tr").remove()
	});
	
	// Submit List of Customer to Back-End server
	$('#postCustomersBtn').click(function(){
		ajaxPost();
	});
	
    function ajaxPost(){
    	
    	// DO POST
    	$.ajax({
			type : "POST",
			contentType : "application/json",
			accept: 'text/plain',
			url : window.location + "api/customer/save",
			data : JSON.stringify(listCustomers),
			dataType: 'text',
			success : function(result) {
				// clear customer body
				$('#customerTable tbody').empty();
				$('#customerTable').hide();
				
				// re-set customer table list
				listCustomers = [];
				
				// fill successfully message on view
				$("#postResultDiv").html("

" + result + "

"); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); } function resetData(){ $("#name").val(""); $("#age").val(""); $("#street").val(""); $("#postcode").val(""); } })

– Create getrequest.js file:

$( document ).ready(function() {
	
	// GET REQUEST
	$("#getAllCustomersBtnId").click(function(event){
		event.preventDefault();
		ajaxGet();
	});
	
	// DO GET
	function ajaxGet(){
		$.ajax({
			type : "GET",
			url : window.location + "api/customer/all",
			success: function(result){
					$('#resultGetAllCustomerDiv ul').empty();
					var custList = "";
					$.each(result, function(i, customer){
						var customer = "{name: " + customer.name + 
						", age: " + customer.age +
						", street: " + customer.address.street +
						", postcode: " + customer.address.postcode +"}";
						
						$('#resultGetAllCustomerDiv .list-group').append("
  • " + customer + "
  • "); }); // just re-css for result-div $('#resultGetAllCustomerDiv').css({'background-color':'#D16953', 'color':'white', 'padding':'20px 20px 5px 30px'}); // just hide POST button if($('#customerTable').is(":hidden")){ $('#postCustomersBtn').hide(); } }, error : function(e) { $("#getResultDiv").html("Error"); console.log("ERROR: ", e); } }); } })

    IV. Sourcecode

    SpringBootJqueryAjaxPostListObjects



    By grokonez | November 14, 2017.


    Related Posts


    1 thought on “Ajax Jquery post List JavaScript Objects to SpringBoot server | BootStrap”

    Got Something To Say:

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

    *