- Spring Controller
- Serialize Object
- Jquery AJax
- Jquery Ajax with SerializeObject
- Cross Site Request Forgery (CSRF)
example :
@ResponseBody
@RequestMapping(value="/insert-dept", method=RequestMethod.POST)
public void insertDept(@RequestBody Department dept){
System.out.println("department : " + dept.getName());
}$.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;
};$(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 !!');
}
});
});
});$.ajax({
url: baseUrl+'member/save-stage',
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: jQuery.param(dataParam)
});
http://api.jquery.com/jquery.ajax/
$('#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);
}
});
}); <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>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);
}
});