Skip to content

Latest commit

 

History

History
143 lines (128 loc) · 2.83 KB

File metadata and controls

143 lines (128 loc) · 2.83 KB

Ajax with Jquery

Session

  1. Spring Controller
  2. Serialize Object
  3. Jquery AJax
  4. Jquery Ajax with SerializeObject
  5. Cross Site Request Forgery (CSRF)

Spring Controller

example :
@ResponseBody
@RequestMapping(value="/insert-dept", method=RequestMethod.POST)
public void insertDept(@RequestBody Department dept){
	System.out.println("department : " + dept.getName());
}

Serialize Object

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
	   if (!o[this.name].push) {
	       o[this.name] = [o[this.name]];
	   }
	   o[this.name].push(this.value || '');
       } else {
	   o[this.name] = this.value || '';
       }
   });
   return o;
};

Jquery ajax

$(function(){
	var department = {
		id :105,
		name :'kesejahteraan',
		address : 'bogor selatan'
	};

	$('#btn-add-dept').on('click', function(event){
		event.preventDefault();

		$.ajax({
			type: 'POST',
			url : '/home/insert-dept',
			contentType : 'application/json',
			data : JSON.stringify(department),
			success : function(data){
				console.log(data);
			},
			error: function(data){
				console.log('error !!');
			}
		});
	});
});

Jquery Ajax with Method POST

HTML Javascript

$.ajax({
    url: baseUrl+'member/save-stage',
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: jQuery.param(dataParam)
  });

See more

http://api.jquery.com/jquery.ajax/

Jquery Ajax with Serialize Object

$('#add-book').on("click", function(e){
	e.preventDefault();
	var formData = $('#id-form-buku').serializeObject();
	$.ajax({
		url: '/master/buku/save',
		data: JSON.stringify(formData),
		type: 'POST',
		contentType: 'application/json',
		success : function(data){
			console.log(data);
		}
	});
});	

Cross Site Request Forgery (CSRF)

Meta HTML

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<meta name="_csrf" content="${_csrf.token}"/>
		<!-- default header name is X-CSRF-TOKEN -->
	<meta name="_csrf_header" content="${_csrf.headerName}"/>
	<title>Insert title here</title>
</head>

AjaxSetUp and Example

var employee = {
	name : "masyda arrizaqu"
}

function ajaxSetUp(){
	var token = $("meta[name='_csrf']").attr("content");
	var header = $("meta[name='_csrf_header']").attr("content");
	$(document).ajaxSend(function(e, xhr, options) {
		xhr.setRequestHeader(header, token);
	});
}

ajaxSetUp();
$.ajax({
	url : 'saving',
	type: 'POST',
	data: JSON.stringify(employee),
	contentType: 'application/json',
	success: function(data){
		alert('success');
		console.log(data);
	}
});

Reference

  1. https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html

Contact Email

[email protected]