Skip to content

Instantly share code, notes, and snippets.

@eto4detak
Created May 5, 2019 11:05
Show Gist options
  • Save eto4detak/ab9d33667a04cc483439e50913d0e11b to your computer and use it in GitHub Desktop.
Save eto4detak/ab9d33667a04cc483439e50913d0e11b to your computer and use it in GitHub Desktop.
js jq ajax form
;
jQuery(document).ready(function() {
"use strict";
(function($) {
$('input.psych-reg-button[type=submit]').on('click touch', '', function(event) {
var qform = $(this).closest('form')[0];
var data = new FormData(qform);
for (let entry of data) {
if(entry[0] == 'policy'){
return true;
}
};
qform.policy.closest('.check-main').style.color = "#ff0000";
return false;
});
var email = document.querySelector("#email-form");
var qform = document.querySelector("#qform");
$('.quizbox').on('click', '', function(event) {
var data = new FormData(email);
var output = "";
for (const entry of data) {
output = entry[0] + "=" + entry[1] + "\r";
};
data = new FormData(qform);
for (const entry of data) {
output = entry[0] + "=" + entry[1] + "\r";
};
});
// create structure quest psych
// start
$('#qform .backlink').on('click', '', function(event) {
$(this).siblings('.psych-delete-back').html("");
});
function getPsychStartButton(structIndex = '') {
var elements = [];
if(structIndex == ''){
for (let key in formPsych.questioтStructure) {
if(!~key.indexOf(".")){
elements.push({'key' : key,'val': formPsych.questioтStructure[key].val, 'title' : formPsych.questioтStructure[key].title});
}
}
}else{
for (let key in formPsych.questioтStructure) {
var str = new RegExp('^('+structIndex+').(\\w+)$', 'i');
if(~key.search( str)){
elements.push({'key' : key,'val': formPsych.questioтStructure[key].val, 'title' : formPsych.questioтStructure[key].title});
}
}
}
return elements;
}
function getPsychElement(index) {
var elementSlider = [];
$('.psych-form-form-structure').find('.slide').eq(index).find('.quizbox').each(function(index, el) {
elementSlider.push(this);
});
return elementSlider;
}
function setPsychValueButton(elemIndex, structIndex) {
var structure = getPsychStartButton(structIndex);
var elementSlider = getPsychElement(elemIndex);
if(structure.length > 0){
for (var i = 0; i < structure.length; i++) {
$(elementSlider[i]).show();
$(elementSlider[i]).find('.label-text').text(structure[i].val);
if(i == 0){
$(elementSlider[i]).closest('.slide').find('.question-title').text(structure[i].title);
}
$(elementSlider[i]).find('input').val(structure[i].key);
}
for (var i = structure.length; i < elementSlider.length; i++) {
$(elementSlider[i]).hide();
}
}else{
// нет данных, финиш
for (var i = 0; i < elementSlider.length; i++) {
$(elementSlider[i]).hide();
}
$(elementSlider[0]).closest('.radiobuttonwrapper').after(formPsych.htmlStructure);
// location.href = location.pathname;
}
}
setPsychValueButton(0,'');
// click
$('.psych-form-form-structure').on('click', '.quizbox', function(event) {
var data = new FormData(qform);
var slide = $(this).closest('.slide')[0];
let counter = 0;
let elemIndex = 0;
$('.psych-form-form-structure .slide').each(function(index, el) {
counter++;
if(this == slide){
elemIndex = counter;
}
});
for (const entry of data) {
if('avtomatizacia' === entry[0]){
setPsychValueButton(elemIndex,entry[1]);
}
};
});
// $('.psych-form-form-structure').find('.slide').eq(0).find('.quizbox').each(function(index, el) {
// $(this).find('label-text').text();
// });
// copy
$('a.no-max').on('click', '', function(event) {
event.preventDefault();
let clone = $(this).parent().find('input:first').clone();
$(clone).val('');
$(this).before(clone);
});
// dropbox
// $('.nesting-item-input').on('click', '', function(event) {
// event.preventDefault();
// let input = $(this).find('input').val();
// let text = $(this).find('.input-text').text();
// if('' != input){
// $(this).find('input').val('');
// }else{
// $(this).find('input').val(text);
// }
// });
$('.dropdown-list .checkbox-sign').on('click', '', function(event) {
event.preventDefault();
let elClass = $(this).attr('class');
let input = $(this).find('input').val();
let text = $(this).parent().find('.input-text').text();
if(elClass.indexOf('check-yes') + 1){
$(this).find('input').val('');
}else{
$(this).find('input').val(text);
}
});
// checkbox
$('.check-main,.checkbox-sign').on('click', '', function(event) {
// event.preventDefault();
$(this).toggleClass('check-yes');
$(this).parent().find("#psych_supervision").click();
});
$('.checkbox-sign').on('click', '', function(event) {
// event.preventDefault();
if($(this).attr('class').indexOf('check-yes') + 1){
$(this).find('input[type=checkbox]').prop('checked', true);
}else{
$(this).find('input[type=checkbox]').prop('checked', false);
}
});
// mask
$('.input-date').mask('AA.BA.YYYY', {'translation': {
A: {pattern: /[0-9]/},
B: {pattern: /[0-1]/},
Y: {pattern: /[0-9]/}
}
});
$('.input-hours-minute').mask('AA:BA', {'translation': {
A: {pattern: /[0-9]/},
B: {pattern: /[0-5]/},
}
});
$('.input-tel').mask('+7 (000) 000-0000');
$('.input-number').mask('0#');
$('.input-year').mask('A999', {'translation': {
A: {pattern: /[1-2]/},
}
});
// AJAX
// ajax file img
$('.load-btn').on('click', '', function(event) {
event.preventDefault();
$(this).parent().find('input[type=file].download').click();
});
var files; // переменная. будет содержать данные файлов
// // заполняем переменную данными, при изменении значения поля file
$('input[type=file].download.download-photo').on('change', function(event){
files = this.files;
event.stopPropagation(); // остановка всех текущих JS событий
event.preventDefault(); // остановка дефолтного события для текущего элемента - клик для <a> тега
// ничего не делаем если files пустой
if( typeof files == 'undefined' ) return;
// создадим данные файлов в подходящем для отправки формате
var data = new FormData();
$.each( files, function( key, value ){
if(key > 0) return;
data.append( key, value );
});
// добавим переменную идентификатор запроса
data.append( 'action', 'ajax_upload_files' );
data.append( 'nonce', formPsych.nonce );
data.append( 'status', 'photo' );
// AJAX запрос
$.ajax({
url : formPsych.url,
type : 'POST',
data : data,
cache : false,
dataType : 'json',
// отключаем обработку передаваемых данных, пусть передаются как есть
processData : false,
// отключаем установку заголовка типа запроса. Так jQuery скажет серверу что это строковой запрос
contentType : false,
// функция успешного ответа сервера
success : function( respond, status, jqXHR ){
// ОК
if( respond.success ){
$.each( respond.data, function( key, val ){
$('.for-photo img').attr( "src", val );
$('.psych-status-load').text('Сохранено');
} );
}
// error
else {
}
},
// функция ошибки ответа сервера
error: function( jqXHR, status, errorThrown ){
}
});
});
$('input[type=file].download.download-files').on('change', function(event){
files = this.files;
var changeInput = this;
$(changeInput).parent().find('.downloaded-img-wr').each(function(index, el) {
$(this).remove();
});
$.each(files, function(index, file) {
$(changeInput).parent().prepend('<div class="downloaded-img-wr"><img title="'+file.name+'" src="'+formPsych.domen+'/images/image-2.jpg" alt=""><a href="#" class="delete">✕<br></a></div>');
});
// delete
// $('.downloaded-img-wr .delete').on('click', '', function(event) {
// event.preventDefault();
// var title = $(this).parent().find('img').attr('title');
// var inputtt = $(this).parent().parent().find('input');
// var loadFiles = inputtt[0].files;
// var input = changeInput;
// for (var i = 0; i < loadFiles.length; i++) {
// if(loadFiles[i].name == title){
// }
// }
// $(this).remove();
// });
});
// ajax personal
$('.ajax-personal').on('click', '', function(event) {
event.preventDefault();
var field = $(this).parent().find('#field').val();
var field2 = $(this).parent().find('#fieldCity').val();
var field3 = $(this).parent().find('.input-one').val();
var dataForm = {};
dataForm.formName = 'personal';
dataForm.country = field;
dataForm.city = field2;
dataForm.date = field3;
var str = JSON.stringify(dataForm);
var data = {
action: 'update_psych_data',
dataType: 'json',
dataForm: str,
nonce_code: formPsych.nonce
};
jQuery.post(formPsych.url, data, function(response) {
if(response.data !== undefined && response.data.action == 'redirect'){
location.href = response.data.url;
}
});
});
// ajax contact
$('.ajax-contact').on('click', '', function(event) {
event.preventDefault();
let dataForm = {};
dataForm.formName = 'contact';
dataForm.addressConsul = $('#psych-address-consul').val();
dataForm.tel = $('#psych-tel').val();
dataForm.skype = $('#psych-skype').val();
dataForm.social = $('#psych-social').val();
dataForm.messager = $('#psych-messager').val();
dataForm.site = $('#psych-site').val();
var str = JSON.stringify(dataForm);
var data = {
action: 'update_psych_data',
dataType: 'json',
dataForm: str,
nonce_code: formPsych.nonce
};
jQuery.post(formPsych.url, data, function(response) {
if(response.data !== undefined && response.data.action == 'redirect'){
location.href = response.data.url;
}
});
});
// ajax prof
$('.ajax-prof').on('click', '', function(event) {
event.preventDefault();
let dataForm = {};
dataForm.formName = 'prof';
dataForm.yearConsul = $('#psych-year-consul').val();
dataForm.hours = $('#psych-hours-consul').val();
dataForm.specialization = $('#psych-specialization-consul').val();
dataForm.lang = $('#psych-lang-consul').val();
dataForm.child1 = $('#psych-child1').val();
dataForm.child2 = $('#psych-child2').val();
dataForm.child3 = $('#psych-child3').val();
dataForm.aboutMe = $('#psych-about-me').val();
dataForm.catTitles = [];
$.each( $('input[name=psych_tem]'), function( key, value ){
let text =$(value).val();
let check =$(value).parent().parent().find('.check-yes');
// if(text != ''){
// dataForm.catTitles.push(text);
// }
if(check.length >0){
dataForm.catTitles.push(text);
}
});
var str = JSON.stringify(dataForm);
var data = {
action: 'update_psych_data',
dataType: 'json',
dataForm: str,
nonce_code: formPsych.nonce
};
jQuery.post(formPsych.url, data, function(response) {
if(response.data !== undefined && response.data.action == 'redirect'){
location.href = response.data.url;
}
});
});
// ajax ajax-service
$('.ajax-service').on('click', '', function(event) {
event.preventDefault();
let dataForm = {};
dataForm.formName = 'service';
$.each( $('.check-yes'), function( key, value ){
$(value).parent().find('input').each(function(index, el) {
let id =$(this).attr('id');
let value =$(this).val();
dataForm[id] = value;
});
});
dataForm.promotion = $('#promotion').val();
var str = JSON.stringify(dataForm);
var data = {
action: 'update_psych_data',
dataType: 'json',
dataForm: str,
nonce_code: formPsych.nonce
};
jQuery.post(formPsych.url, data, function(response) {
if(response.data !== undefined && response.data.action == 'redirect'){
location.href = response.data.url;
}
});
});
// ajax ajax-edu
$('.ajax-edu').on('click', '', function(event) {
event.preventDefault();
let dataForm = {};
dataForm.formName = 'edu';
let display = $('.switch-div').parent().find('.red-text').css('display');
if(display == 'block'){
dataForm.consults = 0;
}else{
dataForm.consults = 1;
}
// dataForm.supervision = $('#psych_supervision').is(':checked');
if($('.check-main.check-yes').length > 0){
dataForm.supervision = 1;
}else{
dataForm.supervision = 0;
}
var comment_urls = [];
var archive_urls = [];
$.each( $('.comment_urls'), function( key, value ){
var url =$(value).val();
if(url != ''){
comment_urls.push(url);
}
});
$.each( $('.archive_urls'), function( key, value ){
var url =$(value).val();
if(url != ''){
archive_urls.push(url);
}
});
dataForm.comment_urls = comment_urls;
dataForm.archive_urls = archive_urls;
var str = JSON.stringify(dataForm);
var data = {
action: 'update_psych_data',
dataType: 'json',
dataForm: str,
nonce_code: formPsych.nonce
};
jQuery.post(formPsych.url, data, function(response) {
if(response.success && response.data.action == 'saved'){
}
});
var certificateData = new FormData();
let certificate = $('input[name=psych-foto-certificate]')[0].files;
$.each( certificate, function( key, value ){
certificateData.append( key, value );
});
certificateData.append( 'action', 'ajax_upload_files' );
certificateData.append( 'nonce', formPsych.nonce );
certificateData.append( 'status', 'certificate' );
$.ajax({
url : formPsych.url,
type : 'POST',
data : certificateData,
cache : false,
dataType : 'json',
processData : false,
contentType : false,
success : function( respond, status, jqXHR ){
if( respond.success ){
}
else {
}
},
error: function( jqXHR, status, errorThrown ){
}
});
var reviewData = new FormData();
let review = $('input[name=psych-foto-review]')[0].files;
$.each( review, function( key, value ){
reviewData.append( key, value );
});
reviewData.append( 'action', 'ajax_upload_files' );
reviewData.append( 'nonce', formPsych.nonce );
reviewData.append( 'status', 'foto-review' );
$.ajax({
url : formPsych.url,
type : 'POST',
data : reviewData,
cache : false,
dataType : 'json',
processData : false,
contentType : false,
success : function( respond, status, jqXHR ){
if( respond.success ){
}
else {
}
},
error: function( jqXHR, status, errorThrown ){
}
});
});
})(jQuery);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment