Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
var funcObj = [];
/**
* POSTするデータ取得
*/
function getPostData( selectedForm ) {
// POST data.
var postData = {};
selectedForm.find(':input').each(function () {
postData[$(this).attr('name')] = $(this).val();
});
// token CrossSiteRequestForgeries
postData['_token'] = $('meta[name="csrf-token"]').attr('content');
return postData;
}
function csrfSafeMethod(method) {
// HTTP methods that do not require CSRF protection.
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
/**
* ajax通信時のCRSF対策用token設定
*/
function setAjaxToken( token ) {
// ajax --- start --------------------------------------------------
$.ajaxSetup({
crossDomain: false,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", token );
}
}
});
}
$(document).ready(function () {
/**
* ローディング開始
*/
function startLoading() {
console.log("Ajax Start");
$(".btn-action").hide();
$("#loading").show();
// error初期化
$('.error').each(function(){
$(this).hide();
});
// input box初期化
$('.form-group').each( function(){
if ( $(this).hasClass('has-error') ) {
$(this).removeClass( 'has-error' );
}
});
}
/**
* ローディング終了
*/
function finishLoading() {
console.log("Ajax Finish");
$("#loading").hide();
$(".btn-action").show();
}
/**
* ajax実行ボタン押下
*/
$(document).on("click", ".ajax_execute", function (event) {
event.preventDefault();
// start Loading.
startLoading();
var action = $(this).data("action");
var selectedForm = $('.'+$(this).data("form"));
var mode = $(this).data("mode");
// POST data.
var postData = getPostData( selectedForm );
// set token.
setAjaxToken( postData['_token'] );
var ajaxParamas = {};
if ( selectedForm.attr("enctype") ) {
console.log("enctype:"+selectedForm.attr("enctype"))
ajaxParamas["processData"] = false;
ajaxParamas["contentType"] = false;
ajaxParamas["enctype"] = selectedForm.attr("enctype");
postData = new FormData(selectedForm[0]);
}
ajaxParamas["type"] = "POST";
ajaxParamas["url"] = action;
ajaxParamas["data"] = postData;
ajaxParamas["cache"] = false;
ajaxParamas["dataType"] = "json";
// ajax --- start --------------------------------------------------
$.ajax(ajaxParamas)
.success( function(res) {
if ( mode in funcObj ) {
funcObj[ mode ]( res );
}
// finish Loading.
finishLoading();
}).error ( function() {
// finish Loading.
finishLoading();
});
// ajax --- end --------------------------------------------------
return false;
});
$(document).on('click', '.redirect', function() {
var link = $(this).data('link');
if ( link != "" ) {
$(location).attr("href", link);
}
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment